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);
}
}