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
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
<pre class="brush:xml;"><!--Spring Data Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency></pre>
3.2, Configuration file
# Redis configurationredis:
3.3, Configuration class
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
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
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("短信发送错误"); }
Enter 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!