Topic模型
Topic模型是对Routing模型的一种改进,最主要的一点过就是Topic模型使用了通配符。
-
*代表的是一个单词
-
#代表的是0个或多个单词
1.开发生产者
package topic;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import util.RabbitMQUtils;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sudi
* Date: 2020/12/29
* TIME: 20:06
*/
public class Send {
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = RabbitMQUtils.getConnection("192.168.1.18", "/ems", 5672, "ems", "123");
//获取连接通道对象
Channel channel = connection.createChannel();
channel.exchangeDeclare("log_topic","topic");
String routingKey = "info.st.ss";
channel.basicPublish("log_topic", routingKey, null, "hello log_topic".getBytes());
}
}
2.开发消费者1
package topic;
import com.rabbitmq.client.*;
import util.RabbitMQUtils;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sudi
* Date: 2020/12/29
* TIME: 20:11
*/
public class Accept1 {
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = RabbitMQUtils.getConnection("192.168.1.18", "/ems", 5672, "ems", "123");
//获取连接通道对象
Channel channel = connection.createChannel();
String exchangeName = "log_topic";
//声明交换机
channel.exchangeDeclare(exchangeName, "topic");
//创建临时队列
String queueName = channel.queueDeclare().getQueue();
//绑定交换机与临时队列
channel.queueBind(queueName, exchangeName, "info.*");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
}
3.开发消费者2
package topic;
import com.rabbitmq.client.*;
import util.RabbitMQUtils;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created with IntelliJ IDEA
* Description:
* Author: sudi
* Date: 2020/12/29
* TIME: 20:11
*/
public class Accept2 {
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = RabbitMQUtils.getConnection("192.168.1.18", "/ems", 5672, "ems", "123");
//获取连接通道对象
Channel channel = connection.createChannel();
String exchangeName = "log_topic";
//声明交换机
channel.exchangeDeclare(exchangeName, "topic");
//创建临时队列
String queueName = channel.queueDeclare().getQueue();
//绑定交换机与临时队列
channel.queueBind(queueName, exchangeName, "info.#");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
}
4.执行效果
消费者1和消费者2最大的不同就是RoutingKey,消费者1是info.* 消费者2是info.#,而生产者的RoutingKey是info.st.ss所以消费者1没有接收到消息。