springboot整合redis实现简单验证码登录
时间: 2023-07-08 16:40:19 浏览: 71
好的,下面是实现步骤:
1. 添加 Redis 依赖
在 `pom.xml` 文件中添加 Redis 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置 Redis
在 `application.properties` 文件中添加 Redis 相关配置:
```properties
# Redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
spring.redis.timeout=60000
```
3. 编写验证码生成和存储逻辑
编写一个 `VerificationCodeUtil` 工具类,生成验证码并将验证码存储到 Redis 中:
```java
@Component
public class VerificationCodeUtil {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 生成验证码
* @param key 键
* @param expire 过期时间
* @return 验证码
*/
public String generateCode(String key, long expire) {
//生成四位数字的验证码
String code = String.format("%04d", new Random().nextInt(9999));
//将验证码存储到 Redis 中
redisTemplate.opsForValue().set(key, code, expire, TimeUnit.SECONDS);
return code;
}
}
```
4. 编写验证码登录逻辑
编写一个 `LoginController` 控制器,实现验证码登录功能:
```java
@RestController
public class LoginController {
@Autowired
private VerificationCodeUtil verificationCodeUtil;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@PostMapping("/login")
public String login(String phone, String code) {
//从 Redis 中获取验证码
String cacheCode = redisTemplate.opsForValue().get(phone);
if (cacheCode == null) {
return "验证码已过期,请重新获取";
}
if (!cacheCode.equals(code)) {
return "验证码错误";
}
//验证码验证通过,执行登录逻辑
return "登录成功";
}
@GetMapping("/getCode")
public String getCode(String phone) {
//生成验证码并存储到 Redis 中,有效期为60秒
String code = verificationCodeUtil.generateCode(phone, 60);
return code;
}
}
```
至此,我们已经实现了使用 Redis 存储验证码并实现验证码登录的功能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)