SpringBoot&&RabbitMQ邮件场景

SpringBoot&&RabbitMQ邮件场景

Scroll Down

场景描述
上架重点推荐商品后,向用户发送本商品邮件消息。

springboot中实现

POM文件

 <!--rabbitmq 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <!--mail 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

yml相关配置

server:
  # 端口
  port: 8082
spring:
  # 邮件配置
  mail:
    # 邮件服务器地址
    host: smtp.qq.com
    # 协议
    protocol: smtp
    # 编码格式
    default-encoding: utf-8
    # 授权码(在邮箱开通服务时获取)
    password: 自己的授权码
    # 发送者邮箱地址
    username: 598582457@qq.com
    # 端口(不同邮箱端口号不同)
    port: 587

  # rabbitmq配置
  rabbitmq:
    # 用户名
    username: guest
    # 密码
    password: guest
    # 服务器地址
    host: localhost
    # 端口
    port: 5672
    listener:
      simple:
        #开启手动确认
        acknowledge-mode: manual



application入口

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MailApplication {

    public static void main(String[] args){
        SpringApplication.run(MailApplication.class,args);
    }


    @Bean
    public Queue queue(){
        return new Queue("mail.welcome");
    }
}

发送消息Controller

@RestController
public class HelloController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("testRabbitMQ")
    public String testRabbitMQ(){
        rabbitTemplate.convertAndSend("mail.welcome","li");
        return "success";
    }
}

接收消息

@Component
public class MailReceiver {

	private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

	@Autowired
	private JavaMailSender javaMailSender;
	@Autowired
	private MailProperties mailProperties;
	@Autowired
	private TemplateEngine templateEngine;

	@RabbitListener(queues = "mail.welcome")
	public void handler(Message message, Channel channel) {
		MessageHeaders headers = message.getHeaders();
		//消息序号
		long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
		try {
			MimeMessage msg = javaMailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg);
			//发件人
			helper.setFrom(mailProperties.getUsername());
			//收件人
			helper.setTo("xxx");
			//主题
			helper.setSubject("xxx");
			//发送日期
			helper.setSentDate(new Date());
			//邮件内容
			Context context = new Context();

			String mail = templateEngine.process("mail", context);
			helper.setText(mail, true);
			//发送邮件
			javaMailSender.send(msg);
			LOGGER.info("邮件发送成功");
			channel.basicAck(tag, false);
		} catch (Exception e) {
			/**
			 * 手动确认消息
			 * tag:消息序号
			 * multiple:是否确认多条
			 * requeue:是否退回到队列
			 */
			try {
				channel.basicNack(tag,false,true);
			} catch (IOException ex) {
				LOGGER.error("邮件发送失败=========>{}", e.getMessage());
			}
			LOGGER.error("邮件发送失败=========>{}", e.getMessage());
		}
	}
}