Redis installation and simple use in spring-boot

1. Redis installation

  1. Download https://redis.io/download/

  1. installation steps

tar -xzvf redis-7.0.8.tar.gz 

Cut into the folder and execute the following two commands

make
make install PREFIX=/home/xwl/app/redis-7.0.8

Cut into the bin directory and set up soft links

sudo ln /home/xwl/app/redis-7.0.8/bin/redis-server redis-server
sudo ln /home/xwl/app/redis-7.0.8/bin/redis-cli redis-cli

Execute the redis-server command globally to start the redis database, open a new command line and execute redis-cli to operate the database.

2. Use redis in spring-boot

  1. install dependencies

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  1. Add configuration, redis does not set a password by default, it can be modified in redis.conf

spring:
  redis:
    localhost: localhost
    port: 6379
  #  redis有0-15一共16个数据库
    database: 7
    password:
#    listen-pattern: __keyevent@7__:expired
    jedis:
      pool:
        max-active: 50
        max-wait: 3000
        max-idle: 20
        min-idle: 2
    timeout: 5000
  1. Write RedisService

package com.xia.xiatest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //    写入缓存
    public Boolean save(String key, String value) {
        boolean result = false;
        try {
//          30s后失效
            redisTemplate.opsForValue().set(key,value,30, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    //    读取缓存
    public String readRedis(String key) {
        return redisTemplate.opsForValue()
                .get(key);
    }
    //    更新缓存
    public boolean getAndSet(String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //    删除缓存
    public boolean del(String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

3. Taking the verification code sent by email as an example, use redis to set the time limit for sending the verification code

  1. Install mail dependencies

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
  1. Set third-party sending mail configuration

spring:
    mail:
        host: smtp.qq.com
    #      port: 587
        protocol: smtp
        username: 发件人地址
        password: 邮箱里获取的第三方授权码
        default-encoding: UTF-8
        properties:
          mail:
            smtp:
              auth: true
              starttls:
                enable: true
                required: true
  1. Send mail tool class

package com.xia.xiatest.utils;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class EmailUtil {
//    验证邮箱地址是否正确
    public static boolean isValidEmailAddress(String email){
        boolean result = true;
        try {
            InternetAddress internetAddress = new InternetAddress(email);
            internetAddress.validate();

        } catch (AddressException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }
//    产生验证码
    public static String genVertificationCode() {
        String[] strArr = {"0","1","2","3","4","5","6","7","8","9","0","A","B",
                "C","D","E","F","G","H","I","J","K","L","M","N","O", "P","Q","R",
                "S","T", "U","V","W","X","Y","Z","a","b", "c","d","e","f","g","h",
                "i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
//        将数组转为List
        List<String> verificationCharts = Arrays.asList(strArr);
//        打乱顺序
        Collections.shuffle(verificationCharts);
        String result = "";
        for(int i = 0; i < 6; i++) {
            result += verificationCharts.get(i);
        }
        return result;
    }
}
  1. EmailService class

package com.xia.xiatest.service;

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.Service;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private RedisService redisService;

    /**
     * 发送邮件方法
     * @param to        收件人邮件地址
     * @param subject   主题
     * @param text      正文
     */
    public void sendSimpleMessage(String to, String subject, String text) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);
        mailSender.send((simpleMailMessage));
    }

    /**
     * 将邮箱和验证码存入redis
     * @param emailAddress
     * @param verificationCode
     * @return
     */
    public Boolean saveEmailToRedis(String emailAddress, String verificationCode) {
        String exists = redisService.readRedis(emailAddress);
//       如果redis中存在该emailAddress就不再发送验证码
        if(exists == null){
            redisService.save(emailAddress, verificationCode);
            return true;
        }else {
            return false;
        }
    }

}
  1. Use in Controller

    @GetMapping("/sendEmail")
    public Result sendEmail(@RequestParam("emailAddress") String emailAddress) {
//        检查邮件地址是否有效
        boolean validEmailAddress = EmailUtil.isValidEmailAddress(emailAddress);
        if(validEmailAddress){
//            验证该邮箱是否在数据库中已经注册
            boolean r = userService.checkEmailRegistered(emailAddress);
            if(r){
                throw new SystemException(602);
            }else {
                String code = EmailUtil.genVertificationCode();
                boolean send = emailService.saveEmailToRedis(emailAddress,code);
                if(send) {
                    emailService.sendSimpleMessage(emailAddress, Constants.EMAIL_SUBJECT,"您的验证码是:" + code);
                    return Result.success();
                }else{
                    throw new SystemException(603);
                }
            }
        } else {
            throw new SystemException(601);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_33235279/article/details/128918036