使用springboot基于redis实现获得手机验证码之后进行对比demo

在项目中使用redis的用处有很多。通常使用次数最多的就是把经常查询的数据存入到redis中,这样提高了效率,也缓解了数据库的压力。今天基于redis。写一个手机验证码之后进行对比的demo。多学知识,慢慢让自己强大起来!

测试项目之前,首先要保证自己的redis的服务端已经正常开启。下面开始编码:

POM文件引入依赖
 <!--redis依赖配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
配置yml文件
spring:    
  redis:
    host: localhost # Redis服务器地址
    database: 0 # Redis数据库索引(默认为0)
    port: 6379 # Redis服务器连接端口
    password: # Redis服务器连接密码(默认为空)
    jedis:
      pool:
        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8 # 连接池中的最大空闲连接
        min-idle: 0 # 连接池中的最小空闲连接
    timeout: 3000ms # 连接超时时间(毫秒)
# 自定义redis key
redis:
  key:
    prefix:
      authCode: "portal:authCode:"
    expire:
      authCode: 120 # 验证码超期时间    
RedisService(为了项目更好的可读性)
package cn.zxw.service;

/**
 * @author zxw
 * @version 1.0
 * @description redis测试
 * @data: 2020/2/24 15:34
 */
public interface RedisService {
    /**
     * 存储数据
     * @param key redis
     * @param value redis
     */
    void set(String key, String value);

    /**
     * 获取数据
     * @param key redis
     * @return 数据
     */
    String get(String key);

    /**
     * 设置超期时间
     * @param key 对应的key
     * @param expire 对应的时间
     * @return 是否成功
     */
    boolean expire(String key, long expire);

    /**
     * 删除数据
     */
    void remove(String key);

    /**
     * 自增操作
     * @param delta 自增步长
     */
    Long increment(String key, long delta);
}

RedisServiceImpl实现类
package cn.zxw.service.impl;

import cn.zxw.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @version 1.0
 * @description 实现类
 * @data: 2020/2/24 15:36
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String key) {
        //opsForValue 操作字符串的用法
        String value = stringRedisTemplate.opsForValue().get(key);
        return value;
    }

    @Override
    public boolean expire(String key, long expire) {
        stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
        return false;
    }

    @Override
    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Long increment(String key, long delta) {
        stringRedisTemplate.opsForValue().increment(key, delta);
        return null;
    }
}
RegisterMemberService
package cn.zxw.service;

import cn.zxw.bean.result.CommonResult;

/**
 * @author zxw
 * @version 1.0
 * @description 会员注册service
 * @data: 2020/2/24 15:47
 */
public interface RegisterMemberService {
    /**
     * 获得用户验证码
     * @param userPhone 电话号码
     * @return 返回结果
     */
    CommonResult getAuthCode(String userPhone);

    /**
     * 判断验证码是否正确
     * @param userPhone 电话
     * @param authCode 验证码
     * @return 结果
     */
    CommonResult updatePassword(String userPhone, String authCode);
}
RegisterMemberServiceImpl
package cn.zxw.service.impl;

import cn.zxw.bean.result.CommonResult;
import cn.zxw.service.RedisService;
import cn.zxw.service.RegisterMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.Random;

/**
 * @author zxw
 * @version 1.0
 * @description 会员注册实现类
 * @data: 2020/2/24 16:03
 */
@Service
public class RegisterMemberServiceImpl implements RegisterMemberService {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_AUTH_CODE;

    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_TIME_OUT;

    @Override
    public CommonResult getAuthCode(String userPhone) {
        try {
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                sb.append(random.nextInt(10));
            }
            //存放到redis中
            redisService.set(REDIS_KEY_AUTH_CODE + userPhone, sb.toString());
            //设置超时时间
            redisService.expire(REDIS_KEY_AUTH_CODE + userPhone, AUTH_CODE_TIME_OUT);
            return CommonResult.success(sb.toString(), "获得验证码成功");
        } catch (Exception e) {
            return CommonResult.failed("验证码比对失败");
        }
    }

    @Override
    public CommonResult updatePassword(String userPhone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return CommonResult.failed("未输入验证码");
        }
        //获取验证码
        String auth = redisService.get(REDIS_KEY_AUTH_CODE + userPhone);
        Optional<String> optional = Optional.of(auth);
        if (optional.isPresent()) {
            if (optional.equals(authCode)) {
                return CommonResult.success(null, "验证码验证正确");
            } else {
                return CommonResult.failed("验证码比对失败");
            }
        }
        //可以定制需要
        return CommonResult.failed("验证码失效");
    }

}
RegisterMemberController
package cn.zxw.controller;

import cn.zxw.bean.result.CommonResult;
import cn.zxw.service.RegisterMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zxw
 * @version 1.0
 * @description 用户注册
 * @data: 2020/2/24 15:44
 */
@RestController
@RequestMapping("/register")
@Api(tags = "RegisterMemberController", value = "用户会员注册管理")
public class RegisterMemberController {

    @Autowired
    private RegisterMemberService registerMemberService;

    @ApiOperation("获取用户验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.POST)
    public CommonResult getAuthCode(String userPhone) {
        return registerMemberService.getAuthCode(userPhone);
    }

    @ApiOperation("判断验证码是否正确")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public CommonResult updatePassword(@ApiParam(value = "手机号码", required = true) @RequestParam String userPhone,
                                       @ApiParam(value = "验证码",  required = true) @RequestParam String authCode) {
        return registerMemberService.updatePassword(userPhone, authCode);
    }
}

下面开始进行测试:
输入手机号后会获得以下结果
调用获取用户验证码接口返回结果
然后我们取出data的数据,调用第二个接口:
调用对比验证码之后
需要注意的是测试时间不能相隔时间太长,否则会超时!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值