zj
2024-06-03 7479d2c5169265cf29e432a30b22c31073106751
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.nq.utils.email;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
 
import java.util.concurrent.TimeUnit;
 
@Service
public class CodeUtil {
 
    //存储时间
    private static final int EXPIRATION_TIME_IN_MINUTES = 3;
    //键名
    public static final String KEY_PREFIX ="yzm";
    @Autowired
    private StringRedisTemplate redisTemplate;
    public String generateVerificationCode() {
        // 生成6位随机数字验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        String key = KEY_PREFIX+code;
        redisTemplate.opsForValue().set(key, code, EXPIRATION_TIME_IN_MINUTES, TimeUnit.MINUTES);
        return code;
    }
 
    // 验证验证码是否正确
    public boolean verifyCode( String code) {
        String key = KEY_PREFIX+code;
        String storedCode = redisTemplate.opsForValue().get(key);
        return code.equals(storedCode);
    }
 
    //删除redis中验证码
    public void deleteCode(String userId, String key) {
        key = key + userId;
        redisTemplate.delete(key);
    }
 
}