<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
如圖使用redisTemplate 一樣的簡單方便
模擬傳送郵件的情況
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit-test</artifactId> <scope>test</scope> </dependency>
spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.host=192.168.91.128 spring.rabbitmq.port=5672 ## 根據自己情況而定,可以不用 spring.rabbitmq.listener.simple.acknowledge-mode=manual spring.rabbitmq.listener.simple.prefetch=100
寫在組態檔中,由 RabbitProperties 這個類進行讀取,封裝到ConnectionFactory 中。
public class MailConstants { public static final Integer DELIVERING = 0;//訊息投遞中 public static final Integer SUCCESS = 1;//訊息投遞成功 public static final Integer FAILURE = 2;//訊息投遞失敗 public static final Integer MAX_TRY_COUNT = 3;//最大重試次數 public static final Integer MSG_TIMEOUT = 1;//訊息超時時間 public static final String MAIL_QUEUE_NAME = "javaboy.mail.queue"; public static final String MAIL_EXCHANGE_NAME = "javaboy.mail.exchange"; public static final String MAIL_ROUTING_KEY_NAME = "javaboy.mail.routing.key"; }
import org.javaboy.vhr.model.MailConstants; import org.javaboy.vhr.service.MailSendLogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { public final static Logger logger = LoggerFactory.getLogger(RabbitConfig.class); @Autowired CachingConnectionFactory cachingConnectionFactory; //傳送郵件的 @Autowired MailSendLogService mailSendLogService; @Bean RabbitTemplate rabbitTemplate() { RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory); //手動應答返回的標誌 rabbitTemplate.setConfirmCallback((data, ack, cause) -> { String msgId = data.getId(); if (ack) { logger.info(msgId + ":訊息傳送成功"); mailSendLogService.updateMailSendLogStatus(msgId, 1);//修改資料庫中的記錄,訊息投遞成功 } else { logger.info(msgId + ":訊息傳送失敗"); } }); rabbitTemplate.setReturnCallback((msg, repCode, repText, exchange, routingkey) -> { logger.info("訊息傳送失敗"); }); return rabbitTemplate; } @Bean Queue mailQueue() { return new Queue(MailConstants.MAIL_QUEUE_NAME, true); } @Bean DirectExchange mailExchange() { return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME, true, false); } @Bean Binding mailBinding() { return BindingBuilder.bind(mailQueue()).to(mailExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME); } }
@Component public class MailSendTask { @Autowired MailSendLogService mailSendLogService; @Autowired RabbitTemplate rabbitTemplate; @Autowired EmployeeService employeeService; @Scheduled(cron = "0/10 * * * * ?") public void mailResendTask() { List<MailSendLog> logs = mailSendLogService.getMailSendLogsByStatus(); if (logs == null || logs.size() == 0) { return; } logs.forEach(mailSendLog->{ if (mailSendLog.getCount() >= 3) { mailSendLogService.updateMailSendLogStatus(mailSendLog.getMsgId(), 2);//直接設定該條訊息傳送失敗 }else{ mailSendLogService.updateCount(mailSendLog.getMsgId(), new Date()); Employee emp = employeeService.getEmployeeById(mailSendLog.getEmpId()); /** * 引數1:交換機名稱 * 引數2 :路由key * 引數三:資料 * 引數4:作為唯一標識 * */ rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, emp, new CorrelationData(mailSendLog.getMsgId())); } }); } }
@Component public class MailReceiver { public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class); @Autowired JavaMailSender javaMailSender; @Autowired MailProperties mailProperties; @Autowired TemplateEngine templateEngine; @Autowired StringRedisTemplate redisTemplate; @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME) public void handler(Message message, Channel channel) throws IOException { Employee employee = (Employee) message.getPayload(); MessageHeaders headers = message.getHeaders(); Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG); String msgId = (String) headers.get("spring_returned_message_correlation"); if (redisTemplate.opsForHash().entries("mail_log").containsKey(msgId)) { //redis 中包含該 key,說明該訊息已經被消費過 logger.info(msgId + ":訊息已經被消費"); channel.basicAck(tag, false);//確認訊息已消費 return; } //收到訊息,傳送郵件 MimeMessage msg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg); try { helper.setTo(employee.getEmail()); helper.setFrom(mailProperties.getUsername()); helper.setSubject("入職歡迎"); helper.setSentDate(new Date()); Context context = new Context(); context.setVariable("name", employee.getName()); context.setVariable("posName", employee.getPosition().getName()); context.setVariable("joblevelName", employee.getJobLevel().getName()); context.setVariable("departmentName", employee.getDepartment().getName()); //根據模板傳送 String mail = templateEngine.process("mail", context); helper.setText(mail, true); javaMailSender.send(msg); redisTemplate.opsForHash().put("mail_log", msgId, "javaboy"); channel.basicAck(tag, false); logger.info(msgId + ":郵件傳送成功"); } catch (MessagingException e) { //手動應答, tag 訊息id ,、 channel.basicNack(tag, false, true); e.printStackTrace(); logger.error("郵件傳送失敗:" + e.getMessage()); } } }
@RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME) public void handler(Message message, Channel channel) throws IOException { 業務邏輯了 手動接收等等 }
到此這篇關於SpringBoot 中使用RabbtiMq 詳解的文章就介紹到這了,更多相關SpringBoot RabbtiMq 內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45