1.生产者
package net.stxy.one.mqtopicexchange;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ProducerTopicExchange {
public static void main(String[] args) throws Exception {
//1.创建连接工厂,并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2.创建连接
Connection connection = connectionFactory.newConnection();
//3.创建连接通道
Channel channel = connection.createChannel();
//4.声明
String exchangeName = "test_topic_exchange";
String routingKey = "user.save";
String routingKey1 = "user.update";
String routingKey2 = "user.delete";
String routingKey3 = "user.select.lulu";
String msg = "test_topic_exchange连接topic模式测试test.direct";
channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
channel.basicPublish(exchangeName, routingKey1, null, msg.getBytes());
channel.basicPublish(exchangeName, routingKey2, null, msg.getBytes());
channel.basicPublish(exchangeName, routingKey3, null, msg.getBytes());
//5.关闭连接:由小到大
channel.close();
connection.close();
}
}
2.消费者
package net.stxy.one.mqtopicexchange;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
public class ConsumerTopicExchange {
public static void main(String[] args) throws Exception {
//1.创建连接工厂,并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setAutomaticRecoveryEnabled(true);//是否支持自动重连
connectionFactory.setNetworkRecoveryInterval(3000);//每三秒钟重连一次
//2.创建连接
Connection connection = connectionFactory.newConnection();
//3.创建连接通道
Channel channel = connection.createChannel();
//4.声明
String exchangeName = "test_topic_exchange";
String exchangeType = "topic";//exchange直连模式
String queueName = "test_topic_queue";
String routingKey = "user.*";//*匹配接下来一个节点,不匹配user.select.lulu
//String routingKey = "user.#";//匹配接下来所有节点,变型写法#.user
//表示声明一个交换机
channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
//表示声明一个队列
channel.queueDeclare(queueName, true, false, false, null);
//建立绑定关系
channel.queueBind(queueName, exchangeName, routingKey);
//5.创建一个消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
//6.设置channel 1.队列名称,2.自动签收 3.消费者对象
channel.basicConsume(queueName, true, consumer);
//7.获取消息 会一直阻塞。可以设置时间通过
while (true) {
System.out.println("开始消费数据");
Delivery delivery = consumer.nextDelivery();//没有设置时间一直阻塞。
String msg = new String(delivery.getBody());//消息实体body
//System.out.println("消费端收到消息"+msg);
System.err.println("消费端收到消息"+msg);
//Envelope envelope = delivery.getEnvelope();//消息属性
}
}
}