该实例用来测试RabbitMQ发送和接收消息功能并解决以下问题:

问题:RabbitMQ默认使用自动应答ack,当消费者宕机,会导致还未被及时处理的消息丢失

解决方案:开启手动应答ack和失败重传机制

 创建项目,导入相关依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- web应用 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--rabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

 RabbitMQ连接配置

server.port=8888
# rabbitMq 连接配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=test
spring.rabbitmq.password=123456

 编写消息接发组件

常量类:声明交换机,路由键,队列的初始值

public class MQConstant {

    public static final String EXCHANGE_DIRECT_PRODUCT = "exchange.direct.product";

    public static final String ROUTING_KEY = "product";

    public static final String QUEUE_PRODUCT = "queue.product";

}

.1 生产者 producer

Service层相关类,封装发送消息的通用方法

@Component
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * @param exchange //指定消息发送到哪个交换机
     * @param routingKey //指定消息发送到bindingKey与routingKey相同的队列中
     * @param message //发送的消息
     */
    public void sendMessage(String exchange, String routingKey, Object message){
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }
}

Controller层提供web接口发送消息

@RestController
public class RabbitMQController {
    @Autowired
    private RabbitService rabbitService;
    @GetMapping("productMsg/{message}")
    public Integer productMsg(@PathVariable("message") String message) {
        System.out.println("producer生产消息====>" + message);
        // 交换机、路由键参数从以上述常量类中获取
        rabbitService.sendMessage(MQConstant.EXCHANGE_DIRECT_PRODUCT, MQConstant.ROUTING_KEY, message);
        return 1;
    }
}

.2 消费者 consumer

消费者绑定队列,从队列中获取消息并处理

@Component
public class Consumer {
// 消费者binding队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstant.QUEUE_PRODUCT, durable = "true"),
            exchange = @Exchange(value = MQConstant.EXCHANGE_DIRECT_PRODUCT),
            key = {MQConstant.ROUTING_KEY}
    ))
    public void consumerMsg(String msg, Message message, Channel channel) throws IOException {
    //TODO:编写处理任务的逻辑
        System.out.println("consumer消费消息====>" + msg);
    }
}

 测试接发消息

网页访问:http://localhost:8888/productMsg/message1

http://localhost:8888/productMsg/message2

http://localhost:8888/productMsg/message3

控制台输出如下:

 开启手动ACK,失败重试机制

默认情况下RabbiMQ的消息分发策略为 轮询:

、会将队列中的所有消息平均分配给所有消费者,消费者拿到消息后,自动回复ack

、RabbitMQ收到ack后就会将队列中的消息删除

、消费者一个一个处理消息

如果前2步成功完成,第3步还没开始,消费者宕机,这些消息将会彻底丢失。

所以我们一般不会使用默认模式,需要设置手动ACK,保证消息的可靠性。

修改消费者代码即可:

为了演示上述情况,自定义了异常

@Component
public class Consumer {
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstant.QUEUE_PRODUCT, durable = "true"),
            exchange = @Exchange(value = MQConstant.EXCHANGE_DIRECT_PRODUCT),
            key = {MQConstant.ROUTING_KEY}
    ))
    public void consumerMsg(String msg, Message message, Channel channel) throws IOException {
        System.out.println("consumer消费消息====>" + msg);
        try {
            String test = null;
            test.equals("test");
            /**
             * 没有异常就确认消息
             * basicAck(long deliveryTag, boolean multiple)
             * deliveryTag:当前消息在队列中的的索引;
             * multiple:为true的话就是批量确认
             */
          channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            /**
             * 有异常就拒收消息
             * basicNack(long deliveryTag, boolean multiple, boolean requeue)
             * requeue:true为将消息重返当前消息队列,重新发送给消费者;
             *         false将消息丢弃
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}

网页访问:http://localhost:8888/productMsg/message1

RabbitMQ不断重试将消息发送给消费者,直到能够成功返回ACK

因为无法收到消费者回复的ACK,因此队列中消息无法被删除

此时rabbitMQ中队列中消息状态:

只有消费者恢复了正常,重新处理消息,并成功恢复ACK,RabbitMq队列中的消息才会被删除。

 引发的问题

以上解决消息的可靠性问题,却引入了消息被重复消费的新问题?

当前消息被处理完成,没有来得急发送ACK,消费者宕机;

下次消费者重启时,又会收到同样的消息,导致消息被重复消费。

大家都有哪些解决方案呢? ^ = ^

原文链接:https://blog.csdn.net/SjwFdb_1__1/article/details/120506480