# rabbitMQ-sendEmail_test **Repository Path**: chishing/rabbitMQ-sendEmail_test ## Basic Information - **Project Name**: rabbitMQ-sendEmail_test - **Description**: SpringBoot+RabbitMQ 采用本地消息列表的方式来保证100%投递成功 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-04-08 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### rabbittest目录是入门demo 程序的入口在这里 ``` @PostMapping("/send") public ServerResponse sendEmail(@Validated Mail mail,Errors errors){ if (errors.hasErrors()){ String msg = errors.getFieldError().getDefaultMessage(); return ServerResponse.error(msg); } System.out.println(mail); testService.send(mail); return ServerResponse.success("ad"); } ``` 把消息http方式发送到接口后,调用testService发送到rabbitmq,同时在本地保存这条消息的状态 ``` @Override public ServerResponse send(Mail mail) { String msgId = RandomStringUtils.randomNumeric(32); mail.setMsgId(msgId); CorrelationData correlationData = new CorrelationData(msgId); MsgLog msgLog = new MsgLog(msgId, mail, RabbitConfig.MAIL_EXCHANGE_NAME, RabbitConfig.MAIL_ROUTING_KEY_NAME); // 消息入库记录 msgLogMapper.insert(msgLog); /** * 使用路由工作模式发送消息. 至于消息是否发送到Exchange, Exchange是否发送到queue然有人帮我们做了记录 * {@link com.cs.test.config.RabbitConfig#rabbitTemplate()} */ rabbitTemplate.convertAndSend(RabbitConfig.MAIL_EXCHANGE_NAME, RabbitConfig.MAIL_ROUTING_KEY_NAME, MessageHelper.objToMsg(mail), correlationData); return ServerResponse.success(ResponseCode.MAIL_SEND_SUCCESS.getMsg()); } ``` 如果失败了话,使用quartz定时重新发送到rabbitmq ``` /** * 最大投递次数 */ private static final int MAX_TRY_COUNT = 3; /** * 每30s拉取投递失败的消息, 重新投递 */ @Scheduled(cron = "0/30 * * * * ?") public void reSendMsg(){ log.info("开始执行定时任务(重新投递消息)"); // 获取投递失败的消息列表 List msgLogs = msgLogService.selectTimeoutMsg(); for (MsgLog msgLog : msgLogs) { String msgId = msgLog.getMsgId(); if (msgLog.getTryCount() >= MAX_TRY_COUNT){ msgLogService.updateStatus(msgId,Constant.MsgLogStatus.DELIVER_FAIL); log.info("超过最大重试次数,消息投递失败,msgId:{}",msgId); }else { // 投递次数 + 1 msgLogService.updateTryCount(msgId, msgLog.getNextTryTime()); // 重发到rabbit