Topic Exchange使用
介绍Topic Exchangey
- 所有发送到 Topic Exchange的消息被转发到所有关心 Routekeyl中指定 Topici的 Queue上
- Exchange将 Routekey和某 Topic进行模糊匹配此时队列需要绑定一个 Topic
- 符号“#”匹配一个或多个词,符号 * 匹配不多不少一个词例如:“log.#”能够匹配到” log. info.oa"og.*”只会匹配到"log.erro
具体代码实现
消费端
public class CunsumerForTopic {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
String exchangeName = "test_topic_exchange";
String exchangeType = "topic";
String queueName = "test_topic_queue";
String routingKey = "user.*";
channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
channel.queueDeclare(queueName,false,false,false,null);
channel.queueBind(queueName,exchangeName,routingKey);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName,true,consumer);
while (true){
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("收到消息:" + msg);
}
}
}
生产端
public class ProducterForTopic {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
String exchangeName = "test_topic_exchange";
String routingKey1 = "user.save";
String routingKey2 = "user.update";
String routingKey3 = "user.delete.abc";
String msg = "hello";
channel.basicPublish(exchangeName,routingKey1,null,msg.getBytes());
channel.basicPublish(exchangeName,routingKey2,null,msg.getBytes());
channel.basicPublish(exchangeName,routingKey3,null,msg.getBytes());
}
}