一、实现方案图解
- 第一步
将要发送的信息进行对应数据库的录入,并且将发送信息的操作作为一条操作日志录入数据库中设置状态字段status
为0(发送中)。
- 第二步
生产端将消息发送到RabbitMQ服务上。
- 第三步
RabbitMQ接收到消息后,进行回应,告诉生产端已接收到信息,这一步骤需要在生产端进行配置,设置RabbitMQ接收到信息后自动回应。
- 第四步
生产端接收到RabbitMQ的回应后,修改数据库日志表中对应消息的状态字段status
为1(发送成功)。
- 第五步
设置定时任务,定时从数据库日志表中获取状态为0的消息
- 第六步
在定时任务中,将获取的状态为0的消息进行重新发送
- 第七步
在定时任务中,获取的消息记录如果发送次数超过三次,就状态设置为3(发送失败)。
二、数据库设计
CREATE TABLE IF NOT EXISTS `t_order` (
`id` VARCHAR(128) NOT NULL,
`name` VARCHAR(128) NOT NULL,
`message_id` VARCHAR(128) NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `broker_massage_log` (
`message_id` VARCHAR(128) NOT NULL,
`message` VARCHAR(4000) DEFAULT NULL,
`try_count` INT(4) DEFAULT '0',
`status` VARCHAR(10) DEFAULT '',
`next_retry` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY(`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
三、依赖包&配置
以第四章中SpringBoot项目的生产端为例
1.添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--数据库相关-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--rabbitMQ依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<