生产者001
/** * 队列到达最大长度的情况 */ public class Producer001 { private static final String NORMAL_EXCHANGE="normal_exchange"; public static void main(String[] args) throws Exception{ Channel channel = untils.getChannel(); channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT); //该消息用作队列的个数限制 for(int i=0;i<10;i++) { String message="info"+i; channel.basicPublish(NORMAL_EXCHANGE,"zhangsan",null,message.getBytes(StandardCharsets.UTF_8)); System.out.println("生产者发送消息"+message); } } }
消费者001
/** * 队列最大长度的普通消费者 */ public class Consumer001 { //普通交换机 private static final String NORMAL_EXCHANGE="normal_exchange"; //死信交换机 private static final String DEAD_EXCHANGE="dead_exchange"; public static void main(String[] args) throws Exception{ Channel channel = untils.getChannel(); //声明死信交换机,类型为direct channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT); channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT); //声明死信队列 String deadQueue="dead_queue"; channel.queueDeclare(deadQueue,false,false,false,null); //死信队列绑定交换和routingKey值 channel.queueBind(deadQueue,DEAD_EXCHANGE,"lisi"); //正常队列绑定死信队列 Map<String,Object> params=new HashMap<>(); //正常队列设置死信交换机,参数key是固定值 params.put("x-dead-letter-exchange",DEAD_EXCHANGE); //正常队列设置死信routing-key,参数key是固定值 params.put("x-dead-letter-routing-key", "lisi"); //正常队列设置的最大限制长度 params.put("x-max-length",6); System.out.println("等待接收消息...."); String normalQueue="normal_queue"; channel.queueDeclare(normalQueue,false,false,false,params); channel.queueBind(normalQueue,NORMAL_EXCHANGE,"zhangsan"); DeliverCallback deliverCallback=(consumerTag, message) -> { String s = new String(message.getBody(), StandardCharsets.UTF_8); System.out.println("01接收到消息"+s); }; channel.basicConsume(normalQueue,true,deliverCallback,consumerTag -> {}); } }
结果: