zqy
2025-10-14 4502f650f4816e55b5c7bf751ffce3aa0dce72dd
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
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);
    }
}