springboot集成redis缓存之手机验证码


2019-08-12

手机号获取验证码的三种存储方式:

1、采用session方式将验证码放入seeeion中并设置过期时间,用户注册登录发送验证码,然后合适对比;

2、采用数据库存储方式,每次将验证码和用户手机号绑定,然后直接查询数据库比对验证码;

3、采用redis方式将手机号码和获取的验证码放入redis缓存中,然后比对用户名和验证码;

建议采用第一种或第三种,如果此过程操作量较大建议使用第三种,第二种方式往数据库写入数据较频繁。

redis存储方式为“key-字符串,value-对象”。

使用redis缓存方式代码如下:(redis的安装和开启在这里就不说了,下一篇会讲到)

1、首先添加依赖(pom.xml)和配置文件(application.properties):

1   <!--redis依赖配置-->
    2       <dependency>
    3           <groupId>org.springframework.boot</groupId>
    4           <artifactId>spring-boot-starter-data-redis</artifactId>
    5       </dependency>


    1 #redis config
    2 spring.redis.host=localhost    #Redis服务器地址
    3 spring.redis.port=6379      #Redis服务器连接端口

2、创建RedisService.java接口

1 public interface RedisService {
     2 
     3      /**
     4      * 存储数据
     5      */
     6     void set(String key, String value);
     7  
     8     /**
     9      * 获取数据
    10      */
    11     String get(String key);
    12  
    13     /**
    14      * 设置超期时间
    15      */
    16     boolean expire(String key, long expire);
    17  
    18     /**
    19      * 删除数据
    20      */
    21     void remove(String key);
    22  
    23     /**
    24      * 自增操作
    25      * @param delta 自增步长
    26      */
    27     Long increment(String key, long delta);
    28 
    29 }

3、创建RedisServiceImpl.java实现RedisService接口

1 import java.util.concurrent.TimeUnit;
     2 import org.springframework.beans.factory.annotation.Autowired;
     3 import org.springframework.data.redis.core.StringRedisTemplate;
     4 import org.springframework.data.redis.core.ValueOperations;
     5 import org.springframework.stereotype.Service;
     6 import com.example.service.RedisService;
     7 
     8 @Service
     9 public class RedisServiceImpl implements RedisService {
    10     
    11     @Autowired
    12     private StringRedisTemplate stringRedisTemplate;    
    13 
    14     @Override
    15     public void set(String key, String value) {    
    16         ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
    17         ops.set(key, value);
    18 
    19     }
    20 
    21     @Override
    22     public String get(String key) {
    23         ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
    24         return ops.get(key);
    25     }
    26 
    27     @Override
    28     public boolean expire(String key, long expire) {
    29         Boolean expire2 = stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    30         return expire2;
    31     }
    32 
    33     @Override
    34     public void remove(String key) {
    35         stringRedisTemplate.delete(key);
    36     }
    37 
    38     @Override
    39     public Long increment(String key, long delta) {
    40         return stringRedisTemplate.opsForValue().increment(key,delta);
    41     }
    42 }

4、具体实现在用户获取验证码的业务逻辑层 ContractorServiceImpl.java

1 @Service
     2 public class ContractorServiceImpl implements ContractorService {
     3 
     4     @Autowired
     5     ContractorMapper contractorMapper;
     6     @Autowired
     7     RedisService redisService;
     8 
     9   private static long CODE_EXPIRE_SECONDS = 600;    //设置验证码过期时间为600秒
    10 
    11   // 手机号获取验证码
    12     @Override
    13     public Result<String> sendSms(String mobile) {
    14         Contractor contractor = contractorMapper.findContractorByPhone(mobile);
    15         System.out.println("获取验证码2" + contractor);
    16         if (contractor == null) {
    17             return new Result<String>(StatusEnum.USER_NOT_EXIST.getUserStatus(), "用户不存在", null);
    18         } else {
    19             // 生成随机六位数
    20             String code = RandomStringUtils.randomNumeric(6);
    21             System.out.println("code" + code);
    22             redisService.remove(mobile);     //清除未失效的key对应的value值
    23             redisService.set(mobile, code);   //缓存新的key-value值
    24             redisService.expire(mobile, CODE_EXPIRE_SECONDS);  //设置过期时间   CODE_EXPIRE_SECONDS
    25             // SmsUtil.sendContractorCode(contractor, code);         //发送短信工具类
    26             return new Result<String>(StatusEnum.USER_OK.getUserStatus(), "成功", code);
    27         }
    28     }
    29 
    30 
    31   //手机号验证码登录
    32     @Override
    33     public Object loginByPhoneCode(String mobile, String code) {
    34     
    35         String code2 = redisService.get(mobile);   //调用方法根据key获取缓存中对应的验证码
    36         System.out.println(code2 + "code2");
    37         // 根据手机号获取承揽人信息
    38         Contractor contractor = contractorMapper.findContractorByPhone(mobile);
    39         Customer customer = contractorMapper.findCustomerByMobile(mobile);
    40         if (contractor == null) {
    41             return new Result<Contractor>(StatusEnum.USER_NOT_EXIST.getUserStatus(), "用户不存在", null);
    42         } else if(code == null) {
    43             return new Result<Contractor>(StatusEnum.USER_CODE_NOT_NULL.getUserStatus(), "验证码不能为空", null);
    44         } else if (StringUtils.isEmpty(code2)) {    //判断验证码是失效,未取到则为失效
    45             return new Result<Contractor>(StatusEnum.USER_CODE_IS_LOSE.getUserStatus(), "验证码失效", null);
    46         } else if (!"".equals(code2) && !code.equals(code2)) {   //判断接收的验证码是否和缓存中的一致
    47             return new Result<Contractor>(StatusEnum.USER_CODE_IS_ERROR.getUserStatus(), "验证码错误", null);
    48         } else {
    49             return new Result<Customer>(StatusEnum.USER_OK.getUserStatus(), "成功登录", customer);
    50         }
    51     }
    52 }

5、最后在controller层实现方法即可。

6、使用postman进行接口测试

7、查看redis缓存是否存在(使用Redis桌面管理器)

具体操作这里就不说了,在下一篇会介绍到。


原文链接:https://www.cnblogs.com/H-Dream/p/11342500.html