手机验证码(java+redis)

import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.io.OutputStream;
import java.util.Random;

/**
 * @auther cheng
 * @create 2021-11-09-13:34
 */
public class PhoneCode {
    @Test
    public void test1(){
        verifyCode("17852031111");
    }

    @Test
    public void test2(){
        getRedisCode("17852031111","790424");
    }
	
	//生成验证码(随机数)
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        return code;
    }

	//发送验证码
    public static void verifyCode(String phone){
    	//redis连接地址
        Jedis jedis = new Jedis("0.0.0.0",6379,0);
        //密码,没有可以省略
        jedis.auth("123456");
		
		//记录发送次数(设置每天三次)
        String countKey = phone+":count";
        //记录每次的验证码
        String codeKey = phone+":code";
        //获取已发次数
        String count = jedis.get(countKey);

        if(count == null){
        	//为空记录第一次
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
        	//在上次的基础上+1,但不修改过期时间
            jedis.incr(countKey);
        }else if (Integer.parseInt(count)>2){
            System.out.println("今天验证次数超过三次");
            //关闭连接并返回
            jedis.close();
            return;
        }
		
		//少于三次执行:将验证码存到redis中
        String vcode = getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();
        //此处可以将验证码发送给手机
    }
	
	//验证码判断
	//code为手机端输入的验证码
    public static void getRedisCode(String phone,String code){
    	//redis连接地址
        Jedis jedis = new Jedis("0.0.0.0",6379,0);
        //密码,没有可以省略
        jedis.auth("123456");
        //验证码的key
        String codeKey = phone+":code";
        //将要查询的redis中的验证码
        String redisCode = "";
        try {
        	//过期会异常
            redisCode = jedis.get(codeKey);
        }catch (Exception e){
            System.out.println("过期");
        }
        if (redisCode == null){
            System.out.println("过期");
        }else if (redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("错误");
        }
        jedis.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是Spring Boot Redis验证码登录功能的基本步骤: 1. 首先在Spring Boot项目中添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> ``` 2. 创建一个Redis配置类,并配置Redis连接信息: ```java @Configuration public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379)); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 3. 创建一个用户实体类,并添加相应的字段: ```java @Data @AllArgsConstructor @NoArgsConstructor public class User { private String username; private String password; private String email; private String verificationCode; } ``` 4. 创建一个验证码登录控制器,并在其中添加验证码生成和校验逻辑: ```java @RestController public class VerificationCodeLoginController { private final RedisTemplate<String, Object> redisTemplate; public VerificationCodeLoginController(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, @RequestParam String verificationCode) { User user = new User(username, password, null, verificationCode); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<User>> violations = validator.validate(user); if (!violations.isEmpty()) { return "Invalid user information."; } // Get the verification code from Redis. String key = "verification_code:" + username; String storedVerificationCode = (String) redisTemplate.opsForValue().get(key); if (storedVerificationCode == null || !storedVerificationCode.equals(verificationCode)) { return "Invalid verification code."; } // Remove the verification code from Redis. redisTemplate.delete(key); // Log the user in. // ... return "Login successful."; } @GetMapping("/verification-code") public String getVerificationCode(@RequestParam String username) { // Generate a random verification code. String verificationCode = RandomStringUtils.randomNumeric(6); // Save the verification code to Redis. String key = "verification_code:" + username; redisTemplate.opsForValue().set(key, verificationCode, 5, TimeUnit.MINUTES); // Return the verification code. return verificationCode; } } ``` 在以上代码中,`login()`方法用于校验用户名、密码和验证码,并根据校验结果执行登录逻辑。在校验过程中,它首先从Redis中获取该用户的验证码,并与传入的验证码进行比较。如果两者不一致,则返回“Invalid verification code.”,否则从Redis中删除验证码,并执行登录逻辑。`getVerificationCode()`方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值