第七节 SpringBoot整合RabbitMQ手动进行ack确认

亮子 2021-07-22 08:02:18 18127 0 0 0

1、修改配置文件

# 应用名称
spring.application.name=server-shop-recv

# 应用服务 WEB 访问端口
server.port=8090

# rabbit mq
spring.rabbitmq.host=8.142.83.78
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=my_vhost
spring.rabbitmq.username=admin
spring.rabbitmq.password=shengban@1907a

# 手动确认模式
spring.rabbitmq.listener.type=direct
spring.rabbitmq.listener.direct.acknowledge-mode=manual

2、接收执行确认函数

package com.shenmazong.recv.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2022/2/8 15:44
 */

@Component
@Slf4j
public class RecvMessage {

    @RabbitListener(queues = "hello")
    public void onHelloMessage(Message message, Channel channel) {
        String msg = null;
        try {
            // 处理消息
            String s = new String(message.getBody());
            log.info("onHelloMessage:"+s);

            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

参考文章