这个章节就详细介绍一下RabbitMQ路由选择的功能和用法。
所谓路由选择,就是建立在exchange通信的基础上的多路选择功能,简单点说就是我两个channel同时监听同一个exchange时,每个channel只接收自己感兴趣的信息。例如校长发个通知在公告栏里,学生只会看和学生相关的通知,不需要知道关于老师的通知。(当然如果需要也可以查看)
下面就是代码实现了,首先是发送代码:
public class EmitLogDirect {
private static final String EXCHANGE_NAME = "direct_logs";
public static void main(String[] argv)
throws java.io.IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct");//注意exchange的类型是direct
String message="Test message";//定义你要发送的信息
String routingName="Student";//定义你要发送的路由的名字
channel.basicPublish(EXCHANGE_NAME,routingName, null, message.getBytes());//发送消息
System.out.println(" [x] Sent '" + routingName+ "':'" + message + "'");
channel.close();
connection.close();
}
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> 大家可以发现,其实代码和exchange发送类似,事实上,他还是基于exchange方式发送的,从需要定义exchangeName就可以看出来了,他只是在exchange的基础上加上消息头,提醒接收消息的人这个消息是给学生的还是老师的。</span>
下面就是接收的代码:
import com.rabbitmq.client.*;
import java.io.IOException;
public class ReceiveLogsDirect {
private static final String EXCHANGE_NAME = "direct_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct");//同样申明一个direct类型的exchange
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "Student");//队列绑定可绑定多个,重复执行语句即可
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {//消息接收
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);
}
}