Spring Boot integrates Redis and JavaMailSender to realize mailbox registration

Posted by N-Bomb(Nerd) on Wed, 25 Mar 2020 17:59:45 +0100

Opening chapter

Today's websites basically have the function of email registration. After all, they can send users some spam recommendations on a regular basis It is very important.

To get back to the point, first of all, we need to make a few points clear

  • ==What information do you need for email registration? = =

    Basic: email address, password, verification code

  • ==Where is this information? = =

    Email address and password can't be said. They will be used frequently in the future. They have to be put into MySQL. As for the verification code, if it's put into MySQL, you have to create a new field for it, but it's not needed after registration. At this time, redis can solve this problem very well. Moreover, redis can also set the expiration time, and various data types are very convenient.

  • ==How do I send mail? = =

    Spring Boot integrates JavaMailSender, which can be used after importing jar package. It is very convenient

Basic process

  1. Click send email, generate a random verification code in the background and store it in redis, and set the validity period of 5 minutes
  2. Click Register to compare the verification code entered by the user with that in redis

code implementation

Only the core code is posted. Please go to my Github See

Mail server: Mail server address Daquan

  1. Import Maven dependency

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. Configure mail and redis information

    spring:
      # Configure mail
      mail:
        host: smtp.qq.com #Mail server address
        username: xxx #Sender email
        password: xxx #Password
        default-encoding: utf-8
      # Configure redis
      redis:
        database: 0
        host: xxx
        port: 6379
    
    # Sender email
    beetle:
      sender:
        email: xxx
    
  3. Reconfigure the RedisTemplate. The native RedisTemplate has serialization problems and needs to be specified again

    @Configuration
    @AutoConfigureAfter(CommunityApplication.class)
    public class RedisConfig {
    
        /**
         * Because the native redis auto assembly does not set the serialization method when storing the key and value, it creates its own redisTemplate instance
         * @param factory
         * @return
         */
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            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);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // key is serialized by String
            template.setKeySerializer(stringRedisSerializer);
            // The hash key also uses String serialization
            template.setHashKeySerializer(stringRedisSerializer);
            // value serialization is jackson
            template.setValueSerializer(jackson2JsonRedisSerializer);
            // value serialization of hash adopts jackson
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
        }
    }
    
    
  4. Write a method to send e-mail. So far, we have generated and stored the verification code in redis

    public Boolean sendEmail(String email) {
        if(!registered(email)){
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setTo(email);
            simpleMailMessage.setSubject("test");
            //Generate 6-bit random number
            int code = (int) ((Math.random() * 9 + 1) * 100000);
            //Deposit in redis, expiration time 5 minutes
            redisTemplate.opsForValue().set(CODE_PRE + email, code, 5, TimeUnit.MINUTES);
            simpleMailMessage.setText("This is a test email with verification code:" + code);
            simpleMailMessage.setFrom(senderEmail);
            try {
                mailSender.send(simpleMailMessage);
                return true;
            } catch (MailException e) {
                log.error("There was an error sending the message,{}", e);
            }
        }
        return false;
    }
    
  5. When registering, you need to check whether the verification code entered by the user is consistent with that in redis. I will not post other logics of registration

    public boolean checkCode(String email, Integer code) {
        Integer redisCode = (Integer) redisTemplate.opsForValue().get(CODE_PRE + email);
        return redisCode != null && redisCode.equals(code);
    }
    

Effect demonstration

Take a project I recently made as an example to show the source code: Beetle community source code , online address: Beetle community

  • Registration interface

  • redis data

  • Mail received

Topics: Programming Redis Spring MySQL github