【无标题】

Springboot 2.7

yaml
spring:
  rabbitmq:
    host: 192.168.2.188
    port: 5672
    username: root
    password: root
    publisher-confirm-type: correlated #SIMPLE -同步确认(阻塞) CORRELATED-异步确认
    publisher-returns: true # 确认消息是否到达队列 
    listener:
      type: simple # simple-listener 容器使用一个额外线程处理消息, direct-listener(监听器)容器直接使用consumer线程
      simple:
        acknowledge-mode: manual #manual 手动 auto-自动 (无异常直接确认, 有异常无限重试)none- 不重试
        prefetch: 1 #每次只接收一条消息, 处理完成后才接收下一条消息. 默认值是 250
        concurrency: 1 #避免消息堆积, 初始化多个消费者线程
gradle
    api 'org.springframework.boot:spring-boot-starter-amqp'
    api 'org.springframework.amqp:spring-rabbit-test'
config
package com.hz.base.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


@Configuration
@Slf4j
public class RabbitConfig {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public static final String HZ_LOG_QUEUE = "hz_log_queue";
    public static final String HZ_LOG_EXCHANGE = "hz_log_exchange"; 
    public static final String HZ_LOG_TOPIC = "hz_log";
   

    @PostConstruct // 表示在构造方法之后执行
    public void init() {
        // 确认消息是否到达交换机
        this.rabbitTemplate.setConfirmCallback(
                (@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) -> {
                    if (!ack) {
                        log.warn("PRO RabbitConfig 消息没有到达交换机" + cause);
                    }
                });

        // 确认消息是否到达队列
        this.rabbitTemplate.setReturnsCallback(returned -> {
            log.warn("PRO RabbitConfig 消息没有到达队列, returned:{}:", returned);
        });

    }


    /**
     * 日志交换机 适合 通用日志队列和 警察日志队列
     */
    @Bean
    public Exchange logExchange() {
        return ExchangeBuilder.topicExchange(HZ_LOG_EXCHANGE)
                .ignoreDeclarationExceptions()// ignoreDeclarationExceptions 忽略声明异常: 一旦我的属性和已有的队列不一样了, 忽略声明异常, 使用既有的(原来的)就可以了
                .durable(true)
                .build();
    }


    /**
     * 通用日志 队列
     */
    @Bean
    public Queue logQueue() {
        return QueueBuilder.durable(HZ_LOG_QUEUE).build();
    }



    @Bean
    public Binding bindingLog(Queue logQueue, Exchange logExchange) {
        return BindingBuilder.bind(logQueue).to(logExchange).with(HZ_LOG_TOPIC).noargs();
    }


}
ConsumerListener
package com.hz.log.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hz.base.config.RabbitConfig;
import com.hz.log.entity.ManageLog;
import com.hz.log.entity.PoliceLog;
import com.hz.log.service.ManageLogService;
import com.hz.log.service.PoliceLogService;
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;

import javax.annotation.Resource;
import java.io.IOException;


@Component
@Slf4j
public class ConsumerListener {

    @Resource
    private PoliceLogService policeLogService;

    @Resource
    private ManageLogService manageLogService;

    @RabbitListener(queues = RabbitConfig.HZ_LOG_QUEUE)
    public void logListener(String msg, Channel channel, Message message) throws IOException {
        try {
            // 手动确认消息   第二个参数 .批量确认.
            log.info("PRO ConsumerListener.logListener msg:{}", msg);
            if (ObjectUtil.isNotEmpty(msg)) {
                manageLogService.insertManageLog(JSONUtil.toBean(msg, ManageLog.class));
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            log.error("ERROR ConsumerListener.logListener redelivered :{},msg:{}, cause:", redelivered, msg, e);
            // 是否已经重试过
            if (redelivered) {
                // 已经重试过直接拒绝
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                // 未重试过 , 重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                        false, true);

            }
        }
    }

}
MqUtils
package com.hz.base.utils;

import com.hz.common.utils.HzObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *@author shen chen
 *@Date 2023-11-23
 *@Description
 */
@Slf4j
@Component
public class MqUtils {

    private static RabbitTemplate rabbitTemplate;

    @Autowired
    public MqUtils(RabbitTemplate rabbitTemplate) {
        MqUtils.rabbitTemplate = rabbitTemplate;
    }


    /**
     * 发送一个持久化的消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param msg 消息
     */
    public static void sendMsg(String exchange, String routingKey, String msg) {
        if (HzObjectUtil.isAnyEmpty(exchange, msg)) {
            return;
        }


        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }

    /**
     * 发送一个非持久化的消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param msg 消息
     */
    public static void sendMsgNonPersistent(String exchange, String routingKey, String msg) {
        if (HzObjectUtil.isAnyEmpty(exchange, msg)) {
            return;
        }
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        Message message = new Message(msg.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值