直连型交换机(direct exchange)是根据消息携带的路由键(routing key)将消息投递给对应队列的。直连交换机要求Publisher
和Consumer的路由关键字(routingKey)完全相同才会将消息路由到绑定的队列。
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
*类说明:direct类型交换器的生产者
*/
public class DirectProducer {
public final static String EXCHANGE_NAME = "direct_logs";
public static void main(String [] args) throws Exception{
//创建连接、连接到RabbitMQ
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置下连接工厂的连接地址(使用默认端口5672)
connectionFactory.setHost("192.168.19.128");
connectionFactory.setUsername("mark");
connectionFactory.setPassword("123456");
connectionFactory.setVirtualHost("enjoyedu");
//创建连接
Connection connection = connectionFactory.newConnection();
//创建信道
Channel channel = connection.createChannel();
//在信道中设置交换器
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
//申明队列(放在消费者中去做)
//申明路由键\消息体
String[] routeKeys ={"king","mark","james"};
for(int i=0; i<routeKeys.length; i++){
String routeKey = routeKeys[i];
String msg = "Hello RabbitMQ" + (i+1);
//发布消息
channel.basicPublish(EXCHANGE_NAME, routeKey, null, msg.getBytes());
System.out.println("send routeKey is " + routeKey + " and msg is " + msg);
}
channel.close();
connection.close();
}
}
import com.rabbitmq.client.*;
import java.io.IOException;
/**
*类说明:普通的消费者
*/
public class NormalConsumer {
public static void main(String [] args) throws Exception{
//创建连接、连接到RabbitMQ
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置下连接工厂的连接地址(使用默认端口5672)
connectionFactory.setHost("192.168.19.128");
connectionFactory.setUsername("mark");
connectionFactory.setPassword("123456");
connectionFactory.setVirtualHost("enjoyedu");
//创建连接
Connection connection = connectionFactory.newConnection();
//创建信道
Channel channel = connection.createChannel();
//在信道中设置交换器
channel.exchangeDeclare(DirectProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
//申明队列
String queueName="queue-king";
channel.queueDeclare(queueName,false,false,false,null);
//绑定:将队列(queuq-king)与交换器通过 路由键 绑定(king)
String routeKey = "king";
channel.queueBind(queueName,DirectProducer.EXCHANGE_NAME,routeKey);
System.out.println("waiting for message ......");
final 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("receive routeKey is " + envelope.getRoutingKey()+" and message is " + message);
}
};
//消息者正式开始在指定队列上消费(queue-king)
channel.basicConsume(queueName, true, consumer);
}
}