QQ邮箱发送验证码(springboot、redis整合)

目录

 

前置

1.开启POP3/SMTP服务

2.依赖导入

3.写业务

4.测试


前置

说明:实现qq邮箱发送信息,可以不用redis

1.开启POP3/SMTP服务

里面会要求发送短信,并得到密码,这个验证码后面会用到

QQ邮箱发送验证码(springboot、redis整合)_第1张图片

QQ邮箱发送验证码(springboot、redis整合)_第2张图片QQ邮箱发送验证码(springboot、redis整合)_第3张图片

2.依赖导入

email依赖


        
            commons-email
            commons-email
            1.1
        
        
            javax.mail
            mail
            1.4.7
        
        
            javax.activation
            activation
            1.1.1
        

redis依赖

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        


        
            org.apache.commons
            commons-pool2
            2.6.0
        

3.写业务

redis配置类,用的时候直接粘贴

@Configuration//表示配置类
@EnableCaching//表示缓存注解
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
    
}

 application.properties配置

 补充:SMTP协议:smtps(端口465)v.msa(端口587)端口465和587用于电子邮件客户端到电子邮件服务器通信

msm.email=自己邮箱
# host
msm.host=smtp.qq.com
# 端口 587和465都可以
msm.port=587
# 发送短信的密码
msm.password=上面的密码

spring.redis.host=hadoop102
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000

spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

创建一个右键的工具类获取参数

@Component
public class EmailUtils implements InitializingBean {
    @Value("${msm.email}")
    private String email;

    @Value("${msm.host}")
    private String host;

    @Value("${msm.port}")
    private String port;

    @Value("${msm.password}")
    private String password;

    public static String EMAIL;
    public static String HOST;
    public static String PORT;
    public static String PASSWORD;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.EMAIL = email;
        this.HOST = host;
        this.PORT = port;
        this.PASSWORD = password;
    }
}

serviceImpl实现方法

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public Boolean send(Map param, String email) {
        if(StringUtils.isEmpty(email)) return false;
        try {
            SimpleEmail mail = new SimpleEmail();
            mail.setSslSmtpPort(EmailUtils.PORT);
            mail.setHostName(EmailUtils.HOST);
            // 设置密码验证器
            mail.setAuthentication(EmailUtils.EMAIL, EmailUtils.PASSWORD);
            // 设置邮件发送者
            mail.setFrom(EmailUtils.EMAIL);
            mail.addTo(email);
            // 设置邮件编码
            mail.setCharset("UTF-8");
            // 设置邮件主题
            mail.setSubject("浪浪课间");
            // 设置邮件内容
            mail.setMsg("10分钟内有效,您的验证码为:"+param.get("code"));
            // 设置邮件发送时间
            mail.setSentDate(new Date());
            // 发送邮件
            mail.send();
            return true;
        } catch (EmailException e) {
            throw new GuliException(20001,"邮件发送异常");
        }

    }

controller层

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate redisTemplate;
//    发送短信方法
    @GetMapping("send/{email}")
    public R sendMsm(@PathVariable String email){
//        1.先从redis获取验证码,如果获取到直接返回
        String s = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(s)){
            return R.ok();
        }
//        如果redis获取不到,进行邮件的发送
//        生成随机数,传递到邮箱进行发送
        String code= RandomUtil.getFourBitRandom();
        Map param =new HashMap<>();
        param.put("code",code);
//        调用service里面短信调用的方法
        Boolean isSend=msmService.send(param,email);
        if(isSend){
//            发送成功,把发送成功的验证码再放到redis中
//            设置有效时间
//            设置5分钟
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("邮箱发送失败");
        }
    }

}

4.测试

打开swagger接口进行测试

QQ邮箱发送验证码(springboot、redis整合)_第4张图片结果:

邮件:

QQ邮箱发送验证码(springboot、redis整合)_第5张图片

redis获取数据

你可能感兴趣的:(JAVA,spring,boot,java,spring,redis)