消息队列之主题模式
1、主题模式(exchange:topic)
主题模式与路由模式几乎一样,只是主题模式使用了类似正则的方法定义路由
- 例如:队列1路由:good.add/good.update
- 队列2路由:good.#
- 队列1只能收到good.add和good.update,而队列2将能收到所有的good.*
2、生产者代码
public class TopicSend {
private static final String QUEUE_NAME1 = "test_exchange_topic1";
private static final String QUEUE_NAME2 = "test_exchange_topic2";
private static final String EXCHANGE_NAME= "test.topic";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, "topic",false,true,null);
//声明队列1
channel.queueDeclare(QUEUE_NAME1,false,false,true,null);
channel.queueBind(QUEUE_NAME1,EXCHANGE_NAME,"good.add");//绑定路由
channel.queueBind(QUEUE_NAME1,EXCHANGE_NAME,"good.update");//绑定路由
channel.basicQos(1);//保证一次只分发一个
//声明队列2
channel.queueDeclare(QUEUE_NAME2,false,false,true,null);
channel.queueBind(QUEUE_NAME2,EXCHANGE_NAME,"good.#");//绑定路由
channel.basicQos(1);//保证一次只分发一个
for (int i=0;i<5;i++){
String msg="hello router topic!" + i;
channel.basicPublish(EXCHANGE_NAME,"good.ads", null,msg.getBytes());
try {
Thread.sleep(12);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("--send:"+msg);
}
}
channel.close();
connection.close();
}
}
3、消费者代码
public class Consumer_1 {
private static final String QUEUE_NAME = "test_exchange_topic1";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body,"utf-8");
System.out.println("路由的good.add/update信息:"+msg);
try {
Thread.sleep(420);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//手动回执消息
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
channel.basicConsume(QUEUE_NAME,false,consumer);
}
}