生产者
package com.qf.mq2302.routing;
import com.qf.mq2302.utils.MQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public static final String EXCHANGE_NAME="emitlogs";
public static void main(String[] args) throws Exception {
Connection connection = MQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
String msg="hello routing!!";
String routingKey="info";
channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg.getBytes("utf-8"));
消费者1号
package com.qf.mq2302.routing;
import com.qf.mq2302.utils.MQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import java.io.IOException;
public class ReceiveError {
private static final String EXCHANGE_NAME="emitlogs";
public static void main(String[] args) throws Exception {
Connection connection = MQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
String queueName = channel.queueDeclare().getQueue();
String routingKey = "error";
channel.queueBind(queueName,EXCHANGE_NAME,routingKey);
channel.basicConsume(queueName, false, new DeliverCallback() {
public void handle(String consumerTag, Delivery message) throws IOException {
byte[] body = message.getBody();
String msg = new String(body, "utf-8");
channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
消费者2号
package com.qf.mq2302.routing;
import com.qf.mq2302.utils.MQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import java.io.IOException;
public class ReceiveIOther {
private static final String EXCHANGE_NAME="emitlogs";
public static void main(String[] args) throws Exception {
Connection connection = MQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"direct");
String queueName = channel.queueDeclare().getQueue();
String routingKey1 = "error";
String routingKey2 = "info";
String routingKey3 = "warn";
channel.queueBind(queueName,EXCHANGE_NAME,routingKey1);
channel.queueBind(queueName,EXCHANGE_NAME,routingKey2);
channel.queueBind(queueName,EXCHANGE_NAME,routingKey3);
channel.basicConsume(queueName, false, new DeliverCallback() {
public void handle(String consumerTag, Delivery message) throws IOException {
byte[] body = message.getBody();
String routingKey = message.getEnvelope().getRoutingKey();
String msg = new String(body, "utf-8");
channel.basicAck(message.getEnvelope().getDeliveryTag(),false);