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桌面管理器)

具體操作這里就不說了,在下一篇會介紹到。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM