全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

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

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

       <dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-redis</artifactId> 
</dependency> 
<dependency> 
  <groupId>cn.apiclub.tool</groupId> 
  <artifactId>simplecaptcha</artifactId> 
  <version>1.2.2</version> 
</dependency> 

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

spring.redis.database=4 
spring.redis.host=hostname 
spring.redis.password=password 
spring.redis.port=6379 
spring.redis.timeout=2000 
spring.redis.pool.max-idle=8 
spring.redis.pool.min-idle=0 
spring.redis.pool.max-active=8 
spring.redis.pool.max-wait=-1 

3、添加redis数据模版

新增RedisConfig.Java

package com.xiaofangtech.sun.config; 
import org.springframework.context.annotation.Bean; 
import org.springframework.data.redis.connection.RedisConnectionFactory; 
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.data.redis.serializer.StringRedisSerializer; 
public class RedisConfig { 
  @Bean 
  JedisConnectionFactory jedisConnectionFactory() { 
    return new JedisConnectionFactory(); 
  } 
  @Bean RedisTemplate<String, String>redisTemplate(RedisConnectionFactory factory) 
  { 
    RedisTemplate<String, String> template = new RedisTemplate<String, String>(); 
    template.setConnectionFactory(jedisConnectionFactory()); 
    template.setKeySerializer(new StringRedisSerializer()); 
    template.setValueSerializer(new StringRedisSerializer()); 
    return template; 
  } 
} 

4、redis的基本使用(缓存生成的验证码信息)

新建CaptchaModule.java,涉及redis插入操作关键代码

@Autowired 
  private RedisTemplate<String, String> redisTemplate; 
//将验证码以<key,value>形式缓存到redis 
    redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS); 

完整代码

package com.xiaofangtech.sunt.utils; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.util.UUID; 
import java.util.concurrent.TimeUnit; 
import javax.imageio.ImageIO; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.http.MediaType; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
import org.springframework.web.bind.annotation.RestController; 
import cn.apiclub.captcha.Captcha; 
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer; 
import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer; 
@RestController 
@RequestMapping("captcha") 
public class CaptchaModule { 
  @Autowired 
  private RedisTemplate<String, String> redisTemplate; 
  private static int captchaExpires = 3*60; //超时时间3min 
  private static int captchaW = 200; 
  private static int captchaH = 60; 
  @RequestMapping(value = "getcaptcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE) 
  public @ResponseBody byte[] getCaptcha(HttpServletResponse response) 
  { 
    //生成验证码 
    String uuid = UUID.randomUUID().toString(); 
    Captcha captcha = new Captcha.Builder(captchaW, captchaH) 
        .addText().addBackground(new GradiatedBackgroundProducer()) 
        .gimp(new FishEyeGimpyRenderer()) 
        .build(); 
    //将验证码以<key,value>形式缓存到redis 
    redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS); 
    //将验证码key,及验证码的图片返回 
    Cookie cookie = new Cookie("CaptchaCode",uuid); 
    response.addCookie(cookie); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    try { 
      ImageIO.write(captcha.getImage(), "png", bao); 
      return bao.toByteArray(); 
    } catch (IOException e) { 
      return null; 
    } 
  } 
} 

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

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

修改JsonWebToken.java

@Autowired 
  private RedisTemplate<String, String> redisTemplate; 
//验证码校验在后面章节添加 
String captchaCode = loginPara.getCaptchaCode(); 
try { 
  if (captchaCode == null) 
  { 
    throw new Exception(); 
  } 
  String captchaValue = redisTemplate.opsForValue().get(captchaCode); 
  if (captchaValue == null) 
  { 
    throw new Exception(); 
  } 
  redisTemplate.delete(captchaCode); 
  if (captchaValue.compareTo(loginPara.getCaptchaValue()) != 0) 
  { 
    throw new Exception(); 
  } 
} catch (Exception e) { 
  resultMsg = new ResultMsg(ResultStatusCode.INVALID_CAPTCHA.getErrcode(),  
      ResultStatusCode.INVALID_CAPTCHA.getErrmsg(), null); 
  return resultMsg; 
} 

6、测试

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

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

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

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

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


总结

以上所述是小编给大家介绍的实例详解Spring Boot实战之Redis缓存登录验证码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


# spring  # boot  # redis  # 缓存登录验证码  # 基于Redis实现短信验证码登录功能  # Redis实现短信验证码登录的示例代码  # 基于Redis实现短信验证码登录项目示例(附源码)  # Redis进行验证码登录的项目实践  # 验证码  # 小编  # 验证码错误  # 在此  # 基础上  # 给大家  # 在后面  # 并与  # 第三方  # 在前面  # 所述  # 给我留言  # 感谢大家  # 可以查看  # 比对  # 疑问请  # 有任何  # 实现了  # String  # redisTemplate 


相关文章: 北京制作网站的公司排名,北京三快科技有限公司是做什么?北京三快科技?  免费网站制作模板下载,除了易企秀之外还有什么H5平台可以制作H5长页面,最好是免费的?  如何选择高效稳定的ISP建站解决方案?  广平建站公司哪家专业可靠?如何选择?  宝塔建站教程:一键部署配置流程与SEO优化实战指南  网站制作公司广州有几家,广州尚艺美发学校网站是多少?  网站制作企业,网站的banner和导航栏是指什么?  韩国代理服务器如何选?解析IP设置技巧与跨境访问优化指南  建站主机选虚拟主机还是云服务器更好?  建站主机如何选?高性价比方案全解析  如何制作新型网站程序文件,新型止水鱼鳞网要拆除吗?  微网站制作教程,我微信里的网站怎么才能复制到浏览器里?  重庆网站制作公司哪家好,重庆中考招生办官方网站?  宝塔新建站点为何无法访问?如何排查?  详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)  如何通过云梦建站系统实现SEO快速优化?  如何通过wdcp面板快速创建网站?  建站之星多图banner生成与模板自定义指南  建站之星安装模板失败:服务器环境不兼容?  TestNG的testng.xml配置文件怎么写  枣阳网站制作,阳新火车站打的到仙岛湖多少钱?  微信h5制作网站有哪些,免费微信H5页面制作工具?  北京建设网站制作公司,北京古代建筑博物馆预约官网?  如何确认建站备案号应放置的具体位置?  宠物网站制作html代码,有没有专门介绍宠物如何养的网站啊?  北京网页设计制作网站有哪些,继续教育自动播放怎么设置?  定制建站模板如何实现SEO优化与智能系统配置?18字教程  教学论文网站制作软件有哪些,写论文用什么软件 ?  如何通过山东自助建站平台快速注册域名?  如何在云主机上快速搭建多站点网站?  如何快速搭建高效服务器建站系统?  高端智能建站公司优选:品牌定制与SEO优化一站式服务  巅云智能建站系统:可视化拖拽+多端适配+免费模板一键生成  家庭服务器如何搭建个人网站?  企业在线网站设计制作流程,想建设一个属于自己的企业网站,该如何去做?  如何设置并定期更换建站之星安全管理员密码?  如何选择高效可靠的多用户建站源码资源?  兔展官网 在线制作,怎样制作微信请帖?  如何快速启动建站代理加盟业务?  如何通过免费商城建站系统源码自定义网站主题与功能?  小自动建站系统:AI智能生成+拖拽模板,多端适配一键搭建  专业网站制作服务公司,有哪些网站可以免费发布招聘信息?  建站之星伪静态规则如何设置?  网站制作说明怎么写,简述网页设计的流程并说明原因?  建站之星CMS五站合一模板配置与SEO优化指南  小程序网站制作需要准备什么资料,如何制作小程序?  如何选择高效便捷的WAP商城建站系统?  制作网站的过程怎么写,用凡科建站如何制作自己的网站?  建站之星后台密码遗忘?如何快速找回?  C++如何编写函数模板?(泛型编程入门) 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。