SpringBoot项目整合Redis,Rabbitmq发送、消费、存储邮件

简介: SpringBoot项目整合Redis,Rabbitmq发送、消费、存储邮件

📑前言

本文主要是【Rabbitmq】——SpringBoot项目整合Redis,Rabbitmq发送、消费、存储邮件的文章,如果有什么需要改进的地方还请大佬指出⛺️

🎬作者简介:大家好,我是听风与他🥇
☁️博客首页:阿里云主页听风与他
🌄每日一句:狠狠沉淀,顶峰相见

SpringBoot项目整合Redis,Rabbitmq发送、消费、存储邮件

1.导入mail,redis,rabbitmq的依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2.配置application.yml文件

spring:
  mail:
    host: smtp.163.com
    username: 15671190765@163.com
    password: XXX   #此为邮箱的snmp密码
  rabbitmq:
    addresses: localhost
    username: admin #rabbitmq的账号名密码均为admin
    password: admin 
    virtual-host: / #虚拟主机采用默认的/
  data:
    redis:
      port: 6379
      host: localhost #redis均为默认配置及端口,不配置yml也可

3.Rabbitmq配置类:RabbitConfiguration

package com.rabbitmqemail.config;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitConfiguration {
   
   

    @Bean
    public MessageConverter messageConverter(){
   
   
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter converter) {
   
   
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(converter);
        return template;
    }

    //给Bean队列取名为邮件队列
    @Bean("emailQueue")
    public Queue emailQueue(){
   
   
        return QueueBuilder
                .durable("mail")  //给邮件队列取名为email
                .build();
    }


}

Rabbitmq监听类:MailQueueListener

package com.rabbitmqemail.listener;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;
@Component
@RabbitListener(queues = "mail") //指定一下消息队列,该消息队列是mail消息队列
public class MailQueueListener{
   
   

    @Autowired
    JavaMailSender sender;

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

    @RabbitHandler
    public void sendMailMessage(Map<String,Object> data){
   
   
//        System.out.println(data.get("email")+" "+data.get("code"));
        String email = (String) data.get("email");
        Integer code = (Integer) data.get("code");
        SimpleMailMessage  message= createMessage("欢迎注册我们的网站","您的验证码为"+code+",有效时间三分钟,为了保障您的安全,请勿向他人泄露验证码信息。",email);
        System.out.println("message1:"+message.getText());
        if (message == null) return;
        sender.send(message);
    }

    private SimpleMailMessage createMessage(String title,String content,String email){
   
   
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);  //主题
        message.setText(content);   //内容
        message.setTo(email);       //发送目标邮箱
        message.setFrom(username);  //源发送邮箱
        return message;
    }
}

接口类:emailService

package com.rabbitmqemail.service;

public interface emailService {
   
   
    String EmailVerifyCode(String email);
}

接口实现类:emailServiceImpl

package com.rabbitmqemail.service.impl;


import ch.qos.logback.classic.pattern.MessageConverter;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmqemail.service.emailService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class emailServiceImpl implements emailService {
   
   

    @Autowired
    AmqpTemplate amqpTemplate; //将消息队列注册为bean

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public String EmailVerifyCode(String email) {
   
   
        Random random = new Random();
        int code = random.nextInt(899999)+100000;  //生成六位数的验证码
//        System.out.println("email:"+email+" code:"+code);
        Map<String,Object> data = Map.of("email",email,"code",code);
        amqpTemplate.convertAndSend("mail",data); //向消息队列中发送数据
        redisTemplate.opsForValue()
                .set(email,String.valueOf(code),3, TimeUnit.MINUTES);
        //用redis来存取数据
        return null;
    }
}

测试类:RabbitmqEmailApplicationTests

package com.rabbitmqemail;

import com.rabbitmqemail.service.impl.emailServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RabbitmqEmailApplicationTests {
   
   


    @Autowired
    private emailServiceImpl emailService;

    @Test
    void contextLoads() {
   
   
        emailService.EmailVerifyCode("2482893650@qq.com");
    }

}

测试结果:此时指定邮箱已收到验证码

image.png

测试项目开源仓库:

https://gitee.com/zhang-zilong_zzl/Rabbitmq-email

📑文章末尾

image.png

相关文章
|
11月前
|
前端开发 安全 Java
Spring Boot 便利店销售系统项目分包设计解析
本文深入解析了基于Spring Boot的便利店销售系统分包设计,通过清晰的分层架构(表现层、业务逻辑层、数据访问层等)和模块化设计,提升了代码的可维护性、复用性和扩展性。具体分包结构包括`controller`、`service`、`repository`、`entity`、`dto`、`config`和`util`等模块,职责分明,便于团队协作与功能迭代。该设计为复杂企业级应用开发提供了实践参考。
429 0
|
8月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
526 3
|
8月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
840 3
|
8月前
|
存储 缓存 NoSQL
Redis 核心知识与项目实践解析
本文围绕 Redis 展开,涵盖其在项目中的应用(热点数据缓存、存储业务数据、实现分布式锁)、基础数据类型(string 等 5 种)、持久化策略(RDB、AOF 及混合持久化)、过期策略(惰性 + 定期删除)、淘汰策略(8 种分类)。 还介绍了集群方案(主从复制、哨兵、Cluster 分片)及主从同步机制,分片集群数据存储的哈希槽算法。对比了 Redis 与 Memcached 的区别,说明了内存用完的情况及与 MySQL 数据一致性的保证方案。 此外,详解了缓存穿透、击穿、雪崩的概念及解决办法,如何保证 Redis 中是热点数据,Redis 分布式锁的实现及问题解决,以及项目中分布式锁
241 1
|
8月前
|
物联网 Linux 开发者
快速部署自己私有MQTT-Broker-下载安装到运行不到一分钟,快速简单且易于集成到自己项目中
本文给物联网开发的朋友推荐的是GMQT,让物联网开发者快速拥有合适自己的MQTT-Broker,本文从下载程序到安装部署手把手教大家安装用上私有化MQTT服务器。
1955 5
|
8月前
|
Java 关系型数据库 MySQL
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
828 2
|
8月前
|
分布式计算 Java 大数据
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
467 2
|
10月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
329 32
|
8月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
330 0
|
8月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
666 0

相关产品

  • 云消息队列 MQ