思路:将投递失败的消息存入数据库,利用定时任务去定时重试发送消息,重试三次,如果三次都无法投递的话,这时候需要人工干预,去处理消息为什么没有能够投递成功
1. 基础配置
SpringBoot版本:2.0.3
- sql
create table if not exists rabbit.msg_broker
(
id int auto_increment primary key,
retry tinyint default '0' not null comment '尝试投递次数',
status tinyint default '1' not null comment '此时的消息的状态',
reason varchar(1000) default '' not null comment '失败原因',
create_time timestamp default CURRENT_TIMESTAMP not null,
update_time timestamp default CURRENT_TIMESTAMP not null,
corr_id varchar(64) default '' not null comment '消息唯一标识',
message varchar(10000) default '' not null comment '消息体',
rounting_key varchar(20) default '' not null comment '路由键',
constraint msg_broker_corr_id_uindex unique (corr_id)
)comment 'rabbit消息信息';
实体类
package com.itcloud.entity;
import java.util.Date;
public class MsgBroker {
//主键
private Integer id;
//消息唯一标识
private String corrId;
//消息尝试发送次数
private Integer retry;
//消息状态
private Integer status;
//消息发送失败原因
private String reason;
//创建时间
private Date createTime;
//更新时间
private Date updateTime;
//消息体
private String message;
//消息路由键
private String rountingKey;
}
- RabbitApplication.java
这里添加注解:
@EnableScheduling
开启springBoot定时任务功能
/**
* rabbbit 消息可靠性投递最佳实践
* @author ITCloud
*/
@SpringBootApplication
@EnableScheduling
public class RabbitApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitApplication.class, args);
}
}
- application.yml
server:
port: 8077
spring:
rabbitmq:
addresses: 192.168.186.130
port: 5672
username: itcloud
password: itcloud
virtual-host: hmall
listener:
direct:
acknowledge-mode: manual # 设置手动签收
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/rabbit?useSSL=false
username: root
password: HelloJava0903!
- RabbitConfig
常量配置类
package com.itcloud.config;
public interface RabbitConfig {
//其中一个交换机名称
public static final String EXCHANGE_DIRECT = "hmex.direct";
public static final int SENDING_STATUS = 0; //消息正在重试发送
public static final int SUCCESS_STATUS = 1; // 消息发送成功
public static final int FAIL_STATUS = 2; // 消息发送失败
public static final int NOT_FOUNT = -1; //数据不存在
public static final int FIRST_RETRY = 1; //第一次重试
public static