生产者:
package mq.topic;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
/**
* @description topic转发器类型的demo
* @author: gaobh
* @date: 2018/4/25 16:11
* @version: v1.0
*/
public class MqTopicProviderDemo {
private static final String EXCHANGE_NAME = "topic_logs";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String[] routing_keys = new String[]{"kernel.info", "cron.warning", "auth.info", "kernel.critical"};
for (String routing_key : routing_keys) {
String msg = UUID.randomUUID().toString();
channel.basicPublish(EXCHANGE_NAME, routing_key, null, msg.getBytes());
System.out.println(" [x] Sent routingKey = " + routing_key + " ,msg = " + msg + ".");
}
channel.close();
connection.close();
}
}
生产者声明了一个routingKey数组,有三个routingKey,分别循环生成消息。
生产者运行结果:
消费者1:
package mq.topic;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* @description topic转发器类型的demo
* @author: gaobh
* @date: 2018/4/25 16:15
* @version: v1.0
*/
@SuppressWarnings("ALL")
public class MqTopicConsumer1Demo {
private static final String EXCHANGE_NAME = "topic_logs";
private static final String QUEUE_NAME = "topic_queue1";
public static void main(String[] args) throws Exception {
// 创建连接和频道
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "kernel.*");
System.out.println(" [*] Waiting for messages about kernel. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String message = new String(body, "UTF-8");
String routingKey = envelope.getRoutingKey();
System.out.println(" [x] Received routingKey = " + routingKey
+ ",msg = " + message + ".");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
消费者有两个通过routingKey来匹配。
消费者1routingKey=kernel.*
消费者2routingKey=*.critical
消费者消费结果:
观察RabbitMQ后台:
我们代码里不是像之前一样设置的临时队列而是两个持久性队列,
看里面的配置: