SpringBoot整合RabbitMQ完成注册账户时异步发送邮件

SpringBoot 完成邮件的投递

本工程使用了SpringBoot+RabbitMQ+Dubbo+ZooKeeper技术栈

准备工作:

登录自己的开通邮件的 以163为例
单独演示邮件发送代码实现:
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第1张图片
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第2张图片
生成自己唯一的授权码
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第3张图片
然后创建如下工程
email-servcie:负责发送邮件相关
user-api:存放项目的公共代码
user-consumer:存放controller层,用于调用service相关方法
user-service:生产者提供接口给消费者user-consumer调用
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第4张图片
父工程的pom.xml

<modules>
    <module>user-consumermodule>
    <module>user-servicemodule>
    <module>user-apimodule>
modules>

编写email-service

工程结构如下

SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第5张图片
在pom.xml中引入spring-boot-starter-amqp和spring-boot-starter-mail的依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.4.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.itheimagroupId>
    <artifactId>email-serviceartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>email-servicename>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-amqpartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-mailartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

在application.yml配置文件中配置

server:
  port: 8082
spring:
  application:
    name: mqemail
  mail:
    username: [email protected]
    password: XXXXXXXXXXXXXXX
    host: smtp.163.com
    properties:
      mail:
        smtp:
          ssl:
            enable: true
  #配置mq
  rabbitmq:
    virtual-host: email
    username: guest
    password: guest
    addresses: 127.0.0.1:5672

编写发送邮件类SendEmail 完成邮件发送

@Component
public class SendEmail {
    @Resource
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}")
    private String sender;

    public void sendEmail(String email) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("帅哥认证官方");
            message.setText("你好,你是官方认证的大帅哥!");
            message.setTo(email);
            message.setFrom(sender);
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
    }
}

编写测试类EmailController,测试邮件是否能发送成功

@RestController
public class EmailController {
    @Resource
    private SendEmail sendEmail;

    @GetMapping("/sendEmail/{email}")
    public String sendEmail(@PathVariable("email") String email){
        sendEmail.sendEmail(email);
        return "ok";
    }

启动EmailServiceApplication类,在浏览器中输入:http://localhost:8082/sendEmail/邮箱号

SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第6张图片
在这里插入图片描述
说明邮件发送成功!

然后再mq包中编写EmailConsumer类,监听mq队列

@Component
public class EmailConsumer {

    @Resource
    private SendEmail sendEmail;

    @RabbitListener(queues = "email_queue")
    public void reveice(String email){
        sendEmail.sendEmail(email);
        System.out.printf("已发送到%s邮箱",email);
    }
}

此时email-service模块编写完毕。

编写user-api

此模块用于存放项目的公共类
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第7张图片
pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>04usermanager_emailartifactId>
        <groupId>com.itheimagroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>user-apiartifactId>


    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.2version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-extensionartifactId>
            <version>3.3.2version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                    <addResources>trueaddResources>
                configuration>
            plugin>
        plugins>
    build>

project>

在application.yml配置文件中配置数据源和mybatis-plus配置

spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/heimassm?characterEncoding=utf-8&serverTimezone=UTC
    data-username: root
    data-password: 123456
#mybatis-plus
mybatis-plus:
  type-aliases-package: com.itheima.pojo
  configuration:
    #  数据库中如果有类似 如  user_name 等命名,会将 _后的字母大写,这里是为了和实体类对应
    map-underscore-to-camel-case: true

创建表的SQL语句

CREATE TABLE `sp_day01_tb_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
  `password` varchar(100) DEFAULT NULL COMMENT '密码',
  `name` varchar(100) DEFAULT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL COMMENT '年龄',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别,1男性,2女性',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8

User.java

package com.itheima.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;

@Data
//实体类和表建立映射关系
@TableName(value = "sp_day01_tb_user")
public class User implements Serializable {

    @TableId(value = "id",type = IdType.AUTO)
    private Long id;

    // 用户名
    private String userName;

    // 密码
    private String password;

    // 姓名
    private String name;

    // 年龄
    private Integer age;

    // 性别,1男性,2女性
    private Integer sex;

    // 出生日期
    private String birthday;

    // 邮箱
    private String email;
}

UserService.java

public interface UserService extends IService<User> {

    boolean register(User user);
}

编写user-service

模块结构如下:
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第8张图片
pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.4.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.itheimagroupId>
    <artifactId>user-serviceartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>user-servicename>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.itheimagroupId>
            <artifactId>user-apiartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-amqpartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-mailartifactId>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.2version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-extensionartifactId>
            <version>3.3.2version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.apache.dubbogroupId>
            <artifactId>dubbo-spring-boot-starterartifactId>
            <version>2.7.5version>
        dependency>
        <dependency>
            <groupId>org.apache.dubbogroupId>
            <artifactId>dubbo-dependencies-zookeeperartifactId>
            <version>2.7.5version>
            <type>pomtype>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4jgroupId>
                    <artifactId>slf4j-log4j12artifactId>
                exclusion>
            exclusions>
        dependency>
        
    dependencies>
project>

在application.yml中配置

server:
  port: 8081  # 修改 服务tomcat默认端口号

spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/heimassm?characterEncoding=utf-8&serverTimezone=UTC
    data-username: root
    data-password: 123456
  #配置项目热部署
  devtools:
    restart:
      enabled: true
  #配置mq
  rabbitmq:
    virtual-host: email
    username: guest
    password: guest
    addresses: 127.0.0.1:5672
dubbo:
  application:
    name: service
  registry:
    address: zookeeper://127.0.0.1:2181
  protocol:
    name: dubbo
    port: 20880
  scan:
    base-packages: com.itheima.service.impl

UserMapper.java

public interface UserMapper extends BaseMapper<User> {
}

UserServiceImpl.java:
Spring为AMQP提供了统一的消息处理模板:AmqpTemplate,非常方便的发送消息,其发送方法:convertAndSend()
第一个参数是交换机名称
第二个参数是路由规则名
第三个参数是要发送的数据
在这里插入图片描述

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean register(User user) {
        this.save(user);
        //  直接向指定的队列投递消息
        rabbitTemplate.convertAndSend("emailExchange","email",user.getEmail());
        return true;
    }
}

需要在UserServiceApplication启动类中,扫描Mapper所在的包

@SpringBootApplication
@MapperScan(basePackages = "com.itheima.mapper")
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

编写user-consumer

模块结构如下:
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第9张图片
pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.4.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.itheimagroupId>
    <artifactId>user-consumerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>user-consumername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>com.itheimagroupId>
            <artifactId>user-apiartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.2version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-extensionartifactId>
            <version>3.3.2version>
        dependency>

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

        
        <dependency>
            <groupId>org.apache.dubbogroupId>
            <artifactId>dubbo-spring-boot-starterartifactId>
            <version>2.7.5version>
        dependency>
        <dependency>
            <groupId>org.apache.dubbogroupId>
            <artifactId>dubbo-dependencies-zookeeperartifactId>
            <version>2.7.5version>
            <type>pomtype>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4jgroupId>
                    <artifactId>slf4j-log4j12artifactId>
                exclusion>
            exclusions>
        dependency>
        

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                    <addResources>trueaddResources>
                configuration>
            plugin>
        plugins>
    build>
project>

application.yml

server:
  port: 8088  # 修改 服务tomcat默认端口号
spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/heimassm?characterEncoding=utf-8&serverTimezone=UTC
    data-username: root
    data-password: 123456
  #配置项目热部署
  devtools:
    restart:
      enabled: true
#配置日志
logging:
  level:
    com.itheima: debug      # 日志级别 debug

#mybatis-plus
mybatis-plus:
  configuration:
    #   sql日志显示,这里使用标准显示
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
dubbo:
  application:
    name: consumer
  registry:
    address: zookeeper://127.0.0.1:2181
  consumer:
    check: false

UserController.java

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
   
    @PostMapping("register")
    public void register(User user){
        //入库,并发送邮件
        userService.register(user);
        System.out.println("入库操作...");
        System.out.println("发送提示邮件给用户");
    }
}

此时项目代码编写完毕
SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第10张图片

打开http://localhost:15672/#/users/guest这个rabbitmq管理,创建如上图

  • 创建email虚拟机
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第11张图片
  • 常见email_queue队列
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第12张图片
  • 创建emailExchange交换机
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第13张图片
  • 点击emailExchange,使用路由规则:email,绑定email_queue队列
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第14张图片
  • 绑定完成
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第15张图片

测试

  • 打开zkserver.cmd服务
  • 依次运行项目的3个启动类
  • SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第16张图片
  • 打开postman测试
  • SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第17张图片
  • 测试结果
    SQL表中添加了这条数据,并且也收到了邮件
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第18张图片
    SpringBoot整合RabbitMQ完成注册账户时异步发送邮件_第19张图片

你可能感兴趣的:(SpringBoot,队列,rabbitmq,spring,boot,dubbo,java)