Consumer01package cn.cnyasin.rabbit.dead;
import cn.cnyasin.rabbit.utils.RabbitMqUtils;
import com.rabbitmq.client.*;
import java.util.HashMap;
import java.util.Map;
public class Consumer01 {
// 交换机名
public static final String EXCHANGE_NAME_NORMAL = "exchange.normal";
public static final String EXCHANGE_NAME_DEAD = "exchange.dead";
// 队列名
public static final String QUEUE_NAME_NORMAL = "queue.normal";
public static final String QUEUE_NAME_DEAD = "queue.dead";
// 路由key名
public static final String ROUTING_KEY_NORMAL = "routing.normal";
public static final String ROUTING_KEY_DEAD = "routing.dead";
// 信道
public static Channel channel = null;
public static void main(String[] args) throws Exception {
// 初始化
init();
Channel channel = getChannel();
// 接收消息成功回调
DeliverCallback deliverCallback = (String consumerTag, Delivery message) -> {
System.out.println("[*] 成功收到消息:" + new String(message.getBody()));
};
// 接收消息失败回调
CancelCallback cancelCallback = (String consumerTag) -> {
System.out.println("[*] 接收消息失败");
};
System.out.println("[*] 正在等待接收消息。。。");
// 接收消息
channel.basicConsume(QUEUE_NAME_NORMAL, true, deliverCallback, cancelCallback);
}
/**
* 初始化
*
* @throws Exception
*/
public static void init() throws Exception {
Channel channel = getChannel();
// 声明交换机(直接交换机)
channel.exchangeDeclare(EXCHANGE_NAME_NORMAL, BuiltinExchangeType.DIRECT, true);
channel.exchangeDeclare(EXCHANGE_NAME_DEAD, BuiltinExchangeType.DIRECT, true);
// 正常队列附加参数
Map<String, Object> args = new HashMap<>();
// 正常队列设置TTL(不常用),一般都是消息发送方设置消息的TTL
// args.put("x-message-ttl", 10000); //单位毫秒
// 正常队列关联设置死信交换机
args.put("x-dead-letter-exchange", EXCHANGE_NAME_DEAD);
// 正常队列关联设置死信路由key
args.put("x-dead-letter-routing-key", ROUTING_KEY_DEAD);
// 声明队列
channel.queueDeclare(QUEUE_NAME_NORMAL, true, false, false, args);
channel.queueDeclare(QUEUE_NAME_DEAD, true, false, false, null);
// 绑定队列、交换机、路由key
channel.queueBind(QUEUE_NAME_NORMAL, EXCHANGE_NAME_NORMAL, ROUTING_KEY_NORMAL);
channel.queueBind(QUEUE_NAME_DEAD, EXCHANGE_NAME_DEAD, ROUTING_KEY_DEAD);
}
public static Channel getChannel() throws Exception {
if (channel == null) {
setChannel(RabbitMqUtils.getChannel());
}
return channel;
}
public static void setChannel(Channel channel) {
Consumer01.channel = channel;
}
}