Home >Database >Redis >How SpringBoot integrates Redis cache verification code

How SpringBoot integrates Redis cache verification code

王林
王林forward
2023-05-27 21:16:23755browse

1. Introduction

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.

Translation: Redis is An open source in-memory data structure storage system that can be used as: database, cache and message middleware.

Redis is an open source high-performance key-value database developed in C language. The officially provided data can reach **100000** QPS.

QPS (Queries-per-second), the number of queries per second. (Baidu Encyclopedia)

It stores a rich set of value types and is also called a structured NoSQL database.

NoSQL (Not only SQL), not just SQL, refers to non-relational databases in general.

NoSQL database is not meant to replace relational databases, but to supplement them.

Relational Database (RDBMS)

  • MySQL

  • ##Oracle

  • DB2

  • ##SQL Server
  • Non-relational database (NoSQL)

    Redis
  • Mongo db
  • MemCached
  • Redis application scenario

    Cache
  • Task Queue
  • Message Queue
  • Distributed Lock
  • 2. Introduction

There are three Java clients officially recommended by Reddis: Jedis, Lettuce, and Redisson.

Spring integrates the Redis client and provides Spring Data Redis.

The Spring Boot project also provides a corresponding Starter, namely spring-boot-starter-data-redis.

Spring Data Redis is used directly here, and the download and installation process of Redis is not shown.

3. Preliminary configuration

3.1. Coordinate import

After creating the Spring Boot project, add

spring-boot-start-data to pom.xml -Dependency coordinates of redis

<pre class="brush:xml;">&lt;!--Spring Data Redis--&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt; &lt;/dependency&gt;</pre>3.2, Configuration file

Other configurations such as MySQL are ignored here, and only the configuration information of Redis is highlighted

spring:
# Redis configuration

redis:
host: localhost
port: 6379
#Decide according to the password you set
password: 123456
# Operate database No. 0, There are 16 databases by default
database: 0
jedis:
pool:
max-active: 8 # Maximum number of connections
max-wait: 1ms #Maximum blocking waiting time of the connection pool
max-idle: 4 # The maximum idle connection in the connection pool
min-idle: 0 # The minimum idle connection in the connection pool

3.3, Configuration class

Use Specialized client interface operations to integrate Redis into Spring Boot. The RedisTemplate tool class is used here, which is provided by the SpringBoot framework.

RedisTemplate will serialize key and value when processing them, which will cause some problems.

For example: the input key value is

city

, but the key value obtained by redis is \xac]xed\x00\x05t\x00\x04city. Therefore, a special configuration class is needed to specifically deal with the problems caused by RedisTemplate's default serialization processing.

It is worth noting that a new serializer is reloaded to replace the original serializer, which proves that it originally had its own default serializer JdkSerializationRedisSerializer.

/**
 * @classname RedisConfig
 * @description Redis配置类,更换key的默认序列化器
 * @author xBaozi
 * @date 19:04 2022/7/2
 **/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

4. Java operation Redis

Since the code is relatively private here (mainly because I am too lazy to sort out the login and verification code generation interfaces), I will directly use the test class for demonstration here. .

Send verification code

@PostMapping("/sendMsg")
public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
    // 获取需要发送短信的手机号
    String userPhone = user.getPhone();
    if (StringUtils.isNotEmpty(userPhone)) {
        // 随机生成4位验证码
        String checkCode = ValidateCodeUtils.generateValidateCode4String(4);
        // 将生成的验证码保存到Redis中并设置有效期五分钟
        redisTemplate.opsForValue().set(userPhone, checkCode, 5, TimeUnit.MINUTES);
        return Result.success(checkCode);
    }
    return Result.error("短信发送错误");
}

How SpringBoot integrates Redis cache verification codeEnter verification code to log in

@PostMapping("/login")
public Result<User> login(@RequestBody Map map, HttpSession session) {
    log.info("map: {}", map);
    // 获取用户输入信息
    String phone = (String)map.get("phone");
    String code = (String)map.get("code");
    // 从Redis中取出验证码
    String checkCode = redisTemplate.opsForValue().get(phone);
    // 比对验证码是否一致
    if (StringUtils.isNotEmpty(checkCode) && checkCode.equals(code.toLowerCase())) {
        // 将用户id存放到session中
        session.setAttribute("user", user.getId());
        // 登录成功,删除Redis中的验证码
        redisTemplate.delete(phone);
        // 将用户信息返回到前端
        return Result.success(user);
    }
    return Result.error("登录失败,请检查手机号或验证码是否正确");
}

The above is the detailed content of How SpringBoot integrates Redis cache verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete