1、添加依赖
<!--rabbitMq 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、yml配置
spring:
rabbitMq:
host: 10.106.11.37
port: 5672
username: admin
password: 123456
listener:
simple:
#消息采取手动应答ACK
acknowledge-mode: manual
#消息被拒后(即未消费),重新(true)放入队列
default-requeue-rejected: true
#并发数
concurrency: 2
#最大并发数
max-concurrency: 10
#消费重试
retry:
#开启消费者出现异常情况下,进行重试消费,默认false
enabled: true
#最大重试次数,默认为3
max-attempts: 5
#重试间隔时间,默认1000(单位毫秒)
initial-interval: 3000
direct:
#消息开启手动确认
acknowledge-mode: manual
3、示例代码
@RabbitListener(queues = Constants.SALE_GIFT_ORDER_METADATA_QUEUE)
public void execute(Message message, Channel channel) {
String orderType = OrderCommonConstants.ORDER_TYPE_LH;
//Step 1.获取消费数据
if (null == message || null == message.getBody()) {
log.info("接收数据为空......");
return;
}
String msgBody = new String(message.getBody(), StandardCharsets.UTF_8);
try {
log.info("收到数据:{}", msgBody);
Map<String, Object> msgBodyMap = JSON.parseObject(msgBody);
//版本号
if (Objects.isNull(msgBodyMap.get("version"))) {
throw new RuntimeException("版本号参数不能为空");
}
Long currentVersion = Long.valueOf(msgBodyMap.get("version").toString());
//主表
JSONObject jsonObject = (JSONObject) msgBodyMap.get("businessData");
//
Object obj= JSONObject.parseObject(JSON.toJSONString(jsonObject), Object.class);
if (Objects.isNull(obj)) {
throw new RuntimeException("实体为Null");
}
//Step 2.保存数据
int res = save(obj);
if (res == OrderCommonConstants.ADD_LOCK_FAIL) {
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
} else {
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
} catch (JSONException e){
log.error("消息格式异常,收到消息:{}, 错误信息:", msgBody, e);
//记录消费异常日志
//。。。。。保存到数据库
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
log.error("消息消费失败,消息格式异常");
} catch (IOException ioException) {
log.error("消息消费失败,消息格式异常,异常信息", ioException);
}
} catch (Exception e){
log.error("消息异常,收到消息:{}, 错误信息:", msgBody, e);
//记录消费异常日志
//。。。。。保存到数据库
try {
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
log.error("消息消费失败,重新放回队列");
} catch (IOException ioException) {
log.error("消息消费失败,重新放回队列,消息体{},异常信息", msgBody, ioException);
}
}
}