1.引入依赖:
2.ack-nack:
public static void main(String[] args) throws IOException, TimeoutException { //创建连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.159.8"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("tuling"); connectionFactory.setUsername("smlz"); connectionFactory.setPassword("smlz"); connectionFactory.setConnectionTimeout(100000); //创建一个连接 Connection connection = connectionFactory.newConnection(); //创建一个channel Channel channel = connection.createChannel(); //声明交换机 String exchangeName = "tuling.ack.direct"; String exchangeType = "direct"; channel.exchangeDeclare(exchangeName,exchangeType,true,false,null); //声明队列 String queueName = "tuling.ack.queue"; channel.queueDeclare(queueName,true,false,false,null); //交换机绑定队列 String routingKey = "tuling.ack.key"; channel.queueBind(queueName,exchangeName,routingKey); /** * 消费端限流 需要关闭消息自动签收 */ channel.basicConsume(queueName,false,new TulingAckConsumer(channel)); } }
2Ack-nackRabbitMQ producers;
public class AckNackRabbitmqProducer { public static void main(String[] args) throws IOException, TimeoutException { //创建连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.159.8"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("tuling"); connectionFactory.setUsername("smlz"); connectionFactory.setPassword("smlz"); connectionFactory.setConnectionTimeout(100000); //创建一个连接 Connection connection = connectionFactory.newConnection(); //创建一个channel Channel channel = connection.createChannel(); //定义交换机的名称 String exchangeName = "tuling.ack.direct"; String routingKey = "tuling.ack.key"; String msgBody = "你好tuling"; for(int i=0;i<10;i++) { Map<String,Object> infoMap = new HashMap<>(); infoMap.put("mark",i); AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder() .deliveryMode(2)//消息持久化 .contentEncoding("UTF-8") .correlationId(UUID.randomUUID().toString()) .headers(infoMap) .build(); channel.basicPublish(exchangeName,routingKey,basicProperties,(msgBody+i).getBytes()); } } }
TulingAckConsumer:
public class TulingAckConsumer extends DefaultConsumer { private Channel channel; public TulingAckConsumer(Channel channel) { super(channel); this.channel = channel; } public void handleDelivery(String consumerTag,Envelope envelope,AMQP.BasicProperties properties,byte[] body) throws IOException { try{ //模拟业务 Integer mark = (Integer) properties.getHeaders().get("mark"); if(mark != 0 ) { System.out.println("消费消息:"+new String(body)); channel.basicAck(envelope.getDeliveryTag(),false); }else{ throw new RuntimeException("模拟业务异常"); } }catch (Exception e) { System.out.println("异常消费消息:"+new String(body)); //重回队列 //channel.basicNack(envelope.getDeliveryTag(),false,true); //不重回队列 channel.basicNack(envelope.getDeliveryTag(),false,false); } } }