本文主要是通过发送邮件来展示关于RabbitMQ很多方面的知识点, 如:
1.消息发送确认机制
2.消费确认机制
3.消息的重新投递
4.消费幂等性, 等等
二、实现思路
编写发送邮件工具类
编写RabbitMQ配置文件
生产者发起调用
消费者发送邮件 判定是否重复消费 发送邮件成功后修改状态
定时任务定时拉取状态为投递失败的消息, 进行重新投递
项目技术:springboot,RabbitMQ,javaMail,mysql, mybatisPlus
1.创建springboot项目 引入依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.4.RELEASE
com.rabbitmail
rabbit-mail-0921
0.0.1-SNAPSHOT
rabbit-mail-0921
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
com.google.code.gson
gson
com.baomidou
mybatis-plus-boot-starter
3.2.0
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-amqp
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.amqp
spring-rabbit-test
test
org.apache.commons
commons-lang3
3.4
com.google.guava
guava
26.0-jre
joda-time
joda-time
2.10
org.apache.commons
commons-collections4
4.1
org.springframework.boot
spring-boot-maven-plugin
2.application.properties
server.port=8888
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/rabbit_mail?characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
mybatis.mapperLocations = classpath:mapper/**/*.xml
##########################################################
##########################################################
# rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
##########################################################
# 开启confirms回调 P -> Exchange
spring.rabbitmq.publisher-confirms=true
# 开启returnedMessage回调 Exchange -> Queue
spring.rabbitmq.publisher-returns=true
# 设置手动确认(ack) Queue -> C
spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.prefetch=100
##########################################################
## mail
spring.mail.host= smtp.qiye.aliyun.com
spring.mail.username = [email protected]
spring.mail.password= xxxxx
[email protected]
spring.mail.properties.mail.smtp.auth= true
spring.mail.properties.mail.smtp.starttls.enable= true
spring.mail.properties.mail.smtp.starttls.required= true
spring.mail.properties.mail.smtp.ssl.enable= true
spring.mail.default-encoding: utf-8
3.mysql表结构
CREATE TABLE `msg_log` (
`msg_id` varchar(255) NOT NULL DEFAULT '' COMMENT '消息唯一标识',
`msg` text COMMENT '消息体, json格式化',
`exchange` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机',
`routing_key` varchar(255) NOT NULL DEFAULT '' COMMENT '路由键',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态: 0投递中 1投递成功 2投递失败 3已消费',
`try_count` int(11) NOT NULL DEFAULT '0' COMMENT '重试次数',
`next_try_time` datetime DEFAULT NULL COMMENT '下一次重试时间',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`msg_id`),
UNIQUE KEY `unq_msg_id` (`msg_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='消息投递日志'
4.发送邮件util MailUtil
@Component
@Slf4j
public class MailUtil {
@Value("${spring.mail.from}")
private String from;
@Autowired
private JavaMailSender mailSender;
/**
* 发送简单邮件
*
* @param mail
*/
public boolean send(Mail mail) {
String to = mail.getTo();// 目标邮箱
String title = mail.getTitle();// 邮件标题
String content = mail.getContent();// 邮件正文
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(title);
message.setText(content);
try {
mailSender.send(message);
log.info("邮件发送成功");
return true;
} catch (MailException e) {
log.error("邮件发送失败, to: {}, title: {}", to, title, e);
return false;
}
}
}
5.RabbitConfig
@Configuration
@Slf4j
public class RabbitConfig {
@Autowired
private CachingConnectionFactory connectionFactory;
@Autowired
private IMsgLogService msgLogService;
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(converter());
// 消息是否成功发送到Exchange
rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
if (ack) {
log.info("消息成功发送到Exchange");
String msgId = correlationData.getId();
msgLogService.updateStatus(msgId, Constant.MsgLogStatus.DELIVER_SUCCESS);
} else {
log.info("消息发送到Exchange失败, {}, cause: {}", correlationData, cause);
}
});
// 触发setReturnCallback回调必须设置mandatory=true, 否则Exchange没有找到Queue就会丢弃掉消息, 而不会触发回调
rabbitTemplate.setMandatory(true);
// 消息是否从Exchange路由到Queue, 注意: 这是一个失败回调, 只有消息从Exchange路由到Queue失败才会回调这个方法
rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
log.info("消息从Exchange路由到Queue失败: exchange: {}, route: {}, replyCode: {}, replyText: {}, message: {}", exchange, routingKey, replyCode, replyText, message);
});
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter converter() {
return new Jackson2JsonMessageConverter();
}
public static final String MAIL_QUEUE_NAME = "mail.queue";
public static final String MAIL_EXCHANGE_NAME = "mail.exchange";
public static final String MAIL_ROUTING_KEY_NAME = "mail.routing.key";
@Bean
public Queue mailQueue() {
return new Queue(MAIL_QUEUE_NAME, true);
}
@Bean
public DirectExchange mailExchange() {
return new DirectExchange(MAIL_EXCHANGE_NAME, true, false);
}
@Bean
public Binding mailBinding() {
return BindingBuilder.bind(mailQueue()).to(mailExchange()).with(MAIL_ROUTING_KEY_NAME);
}
}
6.单元测试 测试发送消息
@Autowired
IMsgLogService iMsgLogService;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void send(Mail mail) {
String msgId = UUID.randomUUID().toString();
mail.setMsgId(msgId);
MsgLog msgLog = new MsgLog();
msgLog.setMsgId(msgId)
.setMsg(new Gson().toJson(mail))
.setExchange(RabbitConfig.MAIL_EXCHANGE_NAME)
.setRoutingKey( RabbitConfig.MAIL_ROUTING_KEY_NAME);
iMsgLogService.save(msgLog);// 消息入库
CorrelationData correlationData = new CorrelationData(msgId);
rabbitTemplate.convertAndSend(RabbitConfig.MAIL_EXCHANGE_NAME,
RabbitConfig.MAIL_ROUTING_KEY_NAME,
new Gson().toJson(mail),
correlationData);// 发送消息
}
6.MailConsumer消费消息, 发送邮件
其实就完成了3件事: 1.保证消费幂等性, 2.发送邮件, 3.更新消息状态, 手动ack
@Component
@Slf4j
public class MailConsumer {
@Autowired
private IMsgLogService msgLogService;
@Autowired
private MailUtil mailUtil;
@RabbitListener(queues = RabbitMqConfig.MAIL_QUEUE_NAME)
public void consume(String content, Message message, Channel channel) throws IOException {
Mail mail = new Gson().fromJson(content,Mail.class);
log.info("收到消息: {}", mail.toString());
String msgId = mail.getMsgId();
MsgLog msgLog = msgLogService.getById(msgId);
if (null == msgLog || msgLog.getStatus().equals(Constant.MsgLogStatus.CONSUMED_SUCCESS)) {// 消费幂等性
log.info("重复消费, msgId: {}", msgId);
return;
}
MessageProperties properties = message.getMessageProperties();
long tag = properties.getDeliveryTag();
boolean success = mailUtil.send(mail);
if (success) {
msgLogService.updateStatus(msgId, Constant.MsgLogStatus.CONSUMED_SUCCESS);
channel.basicAck(tag, false);// 消费确认
} else {
channel.basicNack(tag, false, true);
}
}
}
7.定时任务重新投递发送失败的消息
@Component
@Slf4j
public class ResendMsg {
@Autowired
private IMsgLogService msgLogService;
@Autowired
private RabbitTemplate rabbitTemplate;
// 最大投递次数
private static final int MAX_TRY_COUNT = 3;
/**
* 每30s拉取投递失败的消息, 重新投递
*/
@Scheduled(cron = "0/30 * * * * ?")
public void resend() {
log.info("开始执行定时任务(重新投递消息)");
System.out.println("开始执行定时任务(重新投递消息)");
List msgLogs = msgLogService.selectTimeoutMsg();
msgLogs.forEach(msgLog -> {
String msgId = msgLog.getMsgId();
if (msgLog.getTryCount() >= MAX_TRY_COUNT) {
msgLogService.updateStatus(msgId, Constant.MsgLogStatus.DELIVER_FAIL);
log.info("超过最大重试次数, 消息投递失败, msgId: {}", msgId);
} else {
msgLogService.updateTryCount(msgId, msgLog.getNextTryTime());// 投递次数+1
CorrelationData correlationData = new CorrelationData(msgId);
rabbitTemplate.convertAndSend(msgLog.getExchange(), msgLog.getRoutingKey(), msgLog.getMsg(), correlationData);// 重新投递
log.info("第 " + (msgLog.getTryCount() + 1) + " 次重新投递消息");
}
});
log.info("定时任务执行结束(重新投递消息)");
}
8.其他相关代码
实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("msg_log")
public class MsgLog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 消息唯一标识
*/
private String msgId;
/**
* 消息体, json格式化
*/
private String msg;
/**
* 交换机
*/
private String exchange;
/**
* 路由键
*/
private String routingKey;
/**
* 状态: 0投递中 1投递成功 2投递失败 3已消费
*/
private Integer status;
/**
* 重试次数
*/
private Integer tryCount;
/**
* 下一次重试时间
*/
private LocalDateTime nextTryTime;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
发送邮件对象 Mail
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Mail {
private String to;
private String title;
private String content;
private String msgId;// 消息id
}
常量类Constant
public class Constant {
public interface LogType {
Integer LOGIN = 1;// 登录
Integer LOGOUT = 2;// 登出
}
public interface MsgLogStatus {
Integer DELIVERING = 0;// 消息投递中
Integer DELIVER_SUCCESS = 1;// 投递成功
Integer DELIVER_FAIL = 2;// 投递失败
Integer CONSUMED_SUCCESS = 3;// 已消费
}
}
MsgLogMapper.java
public interface MsgLogMapper extends BaseMapper {
List selectTimeoutMsg();
}
MsgLogMapper.xml
IMsgLogService.java
public interface IMsgLogService extends IService {
void updateStatus(String msgId, Integer status);
List selectTimeoutMsg();
void updateTryCount(String msgId, LocalDateTime tryTime);
}
MsgLogServiceImpl.java
@Service
public class MsgLogServiceImpl extends ServiceImpl implements IMsgLogService {
@Autowired
private MsgLogMapper msgLogMapper;
@Override
public void updateStatus(String msgId, Integer status) {
MsgLog msgLog = new MsgLog();
msgLog.setMsgId(msgId);
msgLog.setStatus(status);
msgLog.setUpdateTime(LocalDateTime.now());
msgLogMapper.updateById(msgLog);
}
@Override
public List selectTimeoutMsg() {
return msgLogMapper.selectTimeoutMsg();
}
@Override
public void updateTryCount(String msgId, LocalDateTime tryTime) {
LocalDateTime nextTryTime = tryTime.plusMinutes(1);
MsgLog msgLog = new MsgLog();
msgLog.setMsgId(msgId);
msgLog.setNextTryTime(nextTryTime);
msgLogMapper.updateById(msgLog);
}
}