springboot集成rabbitmq实现邮件服务

生产者

pom依赖如下

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-amqpartifactId>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-testartifactId>
	<scope>testscope>
dependency>

RabbitMQ配置

# RabbitMQ配置
spring.rabbitmq.host=*.*.*.*
spring.rabbitmq.port=5672
spring.rabbitmq.username=lazyrabbit
spring.rabbitmq.password=password
spring.rabbitmq.virtual-host=/

mail对应实体类

public class Mail implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 3062479058855881261L;
    private Integer id;
    private String to;
    private String subject;
    private String content;
    
    //getset方法。。。
}

生产者代码实现,通过内置的模板类rabbitTemplate将消息发送到队列中

@Component
public class MailSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(Email email) {
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(email.getId().toString());
        rabbitTemplate.convertAndSend("mail-exchange", // exchange
                "mail.test", // routingKey
                email, // 消息实体
                correlationData);// 消息id,可以以此取得消息
    }
}

测试生产者发送消息

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRabbitmqApplicationTests {

    @Autowired
    private MailSender mailSender;

    @Test
    public void testSend() {
        Email e = new Email();
        e.setId(123456);
        e.setSubject("hello");
        e.setTo("[email protected]");
        e.setContent("全军出击");
        mailSender.send(e);
    }
}

我这里先手动创建了topic类型的交换器(mail-exchange)并绑定了Routing key为mail.*的队列,然后执行测试代码,这时可以在RabbitMQ的管理页面中看到队列中多了一条Message。

消费者

pom依赖如下


<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-amqpartifactId>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-testartifactId>
	<scope>testscope>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

application.properties

server.servlet.context.path=/
server.port=8001

# RabbitMQ配置
spring.rabbitmq.host=*.*.*.*
spring.rabbitmq.port=5672
spring.rabbitmq.username=lazyrabbit
spring.rabbitmq.password=password
# 指定连接到broker的Virtual host
spring.rabbitmq.virtual-host=/
# 消费者配置
# 指定最小的消费者数量
spring.rabbitmq.listener.simple.concurrency=5
# 指定最大的消费者数量
spring.rabbitmq.listener.simple.max-concurrency=10
# 指定Acknowledge的模式.我这里是手工确认
spring.rabbitmq.listener.simple.acknowledge-mode=manual
# 指定一个请求能处理多少个消息,如果有事务的话,必须大于等于transaction数量.
spring.rabbitmq.listener.simple.prefetch=1

# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.qq.com
spring.mail.username=***@qq.com
# QQ邮箱的授权码
spring.mail.password=***
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.default-encoding=UTF-8

消费者代码实现

@Component
public class MailConsummer {

    @Autowired
    MailService mailService;
    @Autowired
    private TemplateEngine templateEngine;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "mail-queue2", durable = "true"), exchange = @Exchange(name = "mail-exchange2", durable = "true", type = "topic"), key = "mail.*"))
    @RabbitHandler
    public void onMailMessage(@Payload Email email, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        System.out.println("-----------收到消息------------");
        // 这里是发送html邮件
        // System.out.println(email.toString());
        // Context context = new Context();
        // context.setVariable("id", email.getContent());
        // String emailContent = templateEngine.process("emailTemplate",
        // context);
        //
        // mailService.sendHtmlMail(email.getTo(), email.getSubject(),
        // emailContent);
        mailService.sendSimpleMail(email.getTo(), email.getSubject(), email.getContent());
        Long d = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        channel.basicAck(d, false);
    }
}

邮件发送服务

@Service
public class MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送纯文本的简单邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            sender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }

    /**
     * 发送html格式的邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = sender.createMimeMessage();

        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            sender.send(message);
            logger.info("html邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }

    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = sender.createMimeMessage();

        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            sender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }

    /**
     * 发送嵌入静态资源(一般是图片)的邮件
     * @param to
     * @param subject
     * @param content 邮件内容,需要包括一个静态资源的id,比如:
     * @param rscPath 静态资源路径和文件名
     * @param rscId 静态资源id
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = sender.createMimeMessage();

        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
}

HTML邮件模板

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Title</title>
    </head>
    <body>
        您好,下面是我的网站地址,<br/>
        <a href="#" th:href="@{ http://www.lazyrabbit.tech?from={from}(from=${from}) }"点击即可访问</a>
    </body>
</html>

启动消费者项目,然后再次执行生产者的测试代码,在邮箱中就可以看到邮件。

你可能感兴趣的:(RabbitMQ)