package com.ruoyi.system.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.Random; import java.util.concurrent.TimeUnit; @Service public class VerificationCodeService { @Autowired private StringRedisTemplate redisTemplate; public String generateCode() { Random random = new Random(); return String.format("%04d", random.nextInt(10000)); } public void saveCode(String username, String code) { String key = "verification_code:" + username; redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES); // 5分钟有效 } public boolean validateCode(String username, String inputCode) { String key = "verification_code:" + username; String storedCode = redisTemplate.opsForValue().get(key); return inputCode.equals(storedCode); } }