Spring Boot实战之Redis缓存登录验证码

非常感谢http://blog.csdn.net/sun_t89/article/details/51944252

Spring Boot技术学习 https://www.itkc8.com

 

spring Boot实战之Redis缓存登录验证码

 

本章简单介绍Redis的配置及使用方法,本文示例代码在前面代码的基础上进行修改添加,实现了使用redis进行缓存验证码,以及校验验证码的过程。

 

1、添加依赖库(添加redis库,以及第三方的验证码库)

 

[html] view plain copy

  1.               <dependency>  
  2.     <groupId>org.springframework.bootgroupId>  
  3.     <artifactId>spring-boot-starter-redisartifactId>  
  4. dependency>  
  5. <dependency>  
  6.     <groupId>cn.apiclub.toolgroupId>  
  7.     <artifactId>simplecaptchaartifactId>  
  8.     <version>1.2.2version>  
  9. dependency>  

 

 

2、在application.properties中添加redis的配置信息

 

[html] view plain copy

  1. spring.redis.database=4  
  2. spring.redis.host=hostname  
  3. spring.redis.password=password  
  4. spring.redis.port=6379  
  5. spring.redis.timeout=2000  
  6. spring.redis.pool.max-idle=8  
  7. spring.redis.pool.min-idle=0  
  8. spring.redis.pool.max-active=8  
  9. spring.redis.pool.max-wait=-1  


3、添加redis数据模版

 

新增RedisConfig.Java

 

[java] view plain copy

  1. package com.xiaofangtech.sun.config;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;  
  5. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  6. import org.springframework.data.redis.core.RedisTemplate;  
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;  
  8.   
  9. public class RedisConfig {  
  10.     @Bean  
  11.     JedisConnectionFactory jedisConnectionFactory() {  
  12.         return new JedisConnectionFactory();  
  13.     }  
  14.       
  15.     @Bean RedisTemplateredisTemplate(RedisConnectionFactory factory)  
  16.     {  
  17.         RedisTemplate template = new RedisTemplate();  
  18.         template.setConnectionFactory(jedisConnectionFactory());  
  19.           
  20.         template.setKeySerializer(new StringRedisSerializer());  
  21.         template.setValueSerializer(new StringRedisSerializer());  
  22.         return template;  
  23.     }  
  24. }  


4、redis的基本使用(缓存生成的验证码信息)
新建CaptchaModule.java,涉及redis插入操作关键代码

 

 

[java] view plain copy

  1. @Autowired  
  2.     private RedisTemplate redisTemplate;  

[java] view plain copy

  1. //将验证码以形式缓存到redis  
  2.         redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS);  

 

 

 

完整代码

 

[java] view plain copy

  1. package com.xiaofangtech.sunt.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.UUID;  
  6. import java.util.concurrent.TimeUnit;  
  7.   
  8. import javax.imageio.ImageIO;  
  9. import javax.servlet.http.Cookie;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.data.redis.core.RedisTemplate;  
  14. import org.springframework.http.MediaType;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17. import org.springframework.web.bind.annotation.ResponseBody;  
  18. import org.springframework.web.bind.annotation.RestController;  
  19.   
  20. import cn.apiclub.captcha.Captcha;  
  21. import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;  
  22. import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer;  
  23.   
  24. @RestController  
  25. @RequestMapping("captcha")  
  26. public class CaptchaModule {  
  27.       
  28.     @Autowired  
  29.     private RedisTemplate redisTemplate;  
  30.       
  31.     private static int captchaExpires = 3*60//超时时间3min  
  32.     private static int captchaW = 200;  
  33.     private static int captchaH = 60;  
  34.       
  35.     @RequestMapping(value = "getcaptcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)  
  36.       
  37.     public @ResponseBody byte[] getCaptcha(HttpServletResponse response)  
  38.     {  
  39.         //生成验证码  
  40.         String uuid = UUID.randomUUID().toString();  
  41.         Captcha captcha = new Captcha.Builder(captchaW, captchaH)  
  42.                 .addText().addBackground(new GradiatedBackgroundProducer())  
  43.                 .gimp(new FishEyeGimpyRenderer())  
  44.                 .build();  
  45.           
  46.         //将验证码以形式缓存到redis  
  47.         redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS);  
  48.           
  49.         //将验证码key,及验证码的图片返回  
  50.         Cookie cookie = new Cookie("CaptchaCode",uuid);  
  51.         response.addCookie(cookie);  
  52.         ByteArrayOutputStream bao = new ByteArrayOutputStream();  
  53.         try {  
  54.             ImageIO.write(captcha.getImage(), "png", bao);  
  55.             return bao.toByteArray();  
  56.         } catch (IOException e) {  
  57.             return null;  
  58.         }  
  59.     }  
  60. }  


5、redis内容的获取(根据key获取验证码)

 

完善前面获取token的流程,在获取token的接口中添加校验验证码的流程(根据登录参数中的验证码id获取验证码内容,并与登录参数中的验证码内容进行比对)

修改JsonWebToken.java

 

[java] view plain copy

  1. @Autowired  
  2.     private RedisTemplate redisTemplate;  

 

[java] view plain copy

  1. //验证码校验在后面章节添加  
  2. String captchaCode = loginPara.getCaptchaCode();  
  3. try {  
  4.     if (captchaCode == null)  
  5.     {  
  6.         throw new Exception();  
  7.     }  
  8.     String captchaValue =  redisTemplate.opsForValue().get(captchaCode);  
  9.     if (captchaValue == null)  
  10.     {  
  11.         throw new Exception();  
  12.     }  
  13.     redisTemplate.delete(captchaCode);  
  14.       
  15.     if (captchaValue.compareTo(loginPara.getCaptchaValue()) != 0)  
  16.     {  
  17.         throw new Exception();  
  18.     }  
  19. catch (Exception e) {  
  20.     resultMsg = new ResultMsg(ResultStatusCode.INVALID_CAPTCHA.getErrcode(),   
  21.             ResultStatusCode.INVALID_CAPTCHA.getErrmsg(), null);  
  22.     return resultMsg;  
  23. }  


6、测试

 

1)请求获取验证码,可以获取到验证码图片,以及在cookie中返回缓存入redis的key值

Spring Boot实战之Redis缓存登录验证码_第1张图片


2)查看redis,可以查看到之前缓存的key value

Spring Boot实战之Redis缓存登录验证码_第2张图片

 

3)登录获取token时,添加验证码参数

如果验证码错误,返回验证码错误

Spring Boot实战之Redis缓存登录验证码_第3张图片

 

验证码正确,且用户名密码正确,返回token

Spring Boot实战之Redis缓存登录验证码_第4张图片

Spring Boot实战之Redis缓存登录验证码_第5张图片

 

Spring Boot技术学习 https://www.itkc8.com

你可能感兴趣的:(Redis,springboot)