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 userId, String code, String key) { key = key + userId; String storedCode = redisTemplate.opsForValue().get(key); return code.equals(storedCode); } //删除redis中验证码 public void deleteCode(String userId, String key) { key = key + userId; redisTemplate.delete(key); } }