前言:
Direct 交换机这个交换机就是一个直接连接交换机,所谓“直接连接交换机”就是:
Producer(生产者)投递的消息被DirectExchange (交换机)转发到通过routingkey绑定到具体的某个Queue(队列),把消息放入队列,然后Consumer从Queue中订阅消息。
对接模式:
采用传统的通讯手段处理消息队列的对接问题,生产者直接发送消息到队列,消费者直接消费队列中的消息,不指定exchange并绑定。
这种需求背景下,有三种情形:
1:生产者指定队列名称(声明),消费者不指定队列,而是直接消费生产者指定的队列
2:生产者声明队列并将消息发送到该队列,消费者也声明该队列,并从该队列消费消息;这里要保证生产者和消费者声明队列时指定的参数要一致
3:生产者指定队列,不声明队列,而是直接将消息发送到该队列,消费者声明该队列,并从该队列接收消息;
以下是实际生产中对接第3种模式的代码片段
生产者代码:
//消息生产者
public class DirectBoss {
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
try {
//主机
factory.setHost("");
//端口
factory.setPort();
//虚拟主机
factory.setVirtualHost("");
//用户名
factory.setUsername("");
//密码
factory.setPassword("");
//创建连接
Connection connection = factory.newConnection();
//创建通道
Channel channel = connection.createChannel();//要发布的消息
String message = "SUCCESS";
//消息发布 test.request.1 队列名称
channel.basicPublish("", "test.request.1", null, message.getBytes());
channel.close();
connection.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
消费者代码
public class DirectWorker {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("");
factory.setPassword("");
factory.setHost("");
factory.setPort();
// 创建连接和通道
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 这里声明队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
// 消费者直接从队列中消费
channel.basicConsume(QUEUE_NAME, true, consumer);
while(true){
QueueingConsumer.Delivery de = consumer.nextDelivery();
String result = new String(de.getBody(),"UTF-8");
System.out.println(result);
}
}
}
pom.xml文件导入jar包
<!-- 集成rabbitmq -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.4.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>http-client</artifactId>
<version>2.1.0.RELEASE</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>