SpringBoot集成Redis实现验证码的简单案例

时间:2022-06-28 11:49:39

前言 一次学习过程中简单的记录

 

一、下载安装Redis

这里就不多说了,下载安装好Redis,最好是把Redis Desktop Manager一起安装了,可视化看的舒服一点。

 

二、代码部分

1.引入库,配置yml

引入Redis依赖

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

这里就简单配置做示例,小伙伴们根据自己的业务需求来配置哈~

server:
  port: 8081
spring:
  redis:
    database: 3
    jedis:
      pool:
        max-active: 8
        max-wait: -1
    lettuce:
      pool:
        min-idle: 0
    timeout: 5000

2.编写RedisConfig

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericFastJsonRedisSerializer valueSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 序列化 key 和 value
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

3.编写RedisUtils

@Component
public class RedisClient {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /*
     * @ClassName RedisClient
     * @Desc TODO   设置缓存(没有时间限制)
     * @Date 2021-07-24 16:11
     * @Version 1.0
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /*
     * @ClassName RedisClient
     * @Desc TODO   设置缓存(有时间限制,单位为 秒)
     * @Date 2021-07-24 16:11
     * @Version 1.0
     */
    public void set(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /*
     * @ClassName RedisClient
     * @Desc TODO   删除缓存,并返回是否删除成功
     * @Date 2021-07-24 16:11
     * @Version 1.0
     */
    public boolean delete(String key) {
        redisTemplate.delete(key);
        // 如果还存在这个 key 就证明删除失败
        if (redisTemplate.hasKey(key)) {
            return false;
            // 不存在就证明删除成功
        } else {
            return true;
        }
    }

    /*
     * @ClassName RedisClient
     * @Desc TODO   取出缓存
     * @Date 2021-07-24 16:12
     * @Version 1.0
     */
    public Object get(String key) {
        if (redisTemplate.hasKey(key)) {
            return redisTemplate.opsForValue().get(key);
        } else {
            return null;
        }
    }

    /*
     * @ClassName RedisClient
     * @Desc TODO   获取失效时间(-2:失效 / -1:没有时间限制)
     * @Date 2021-07-24 16:15
     * @Version 1.0
     */
    public long getExpire(String key) {
        // 判断是否存在
        if (redisTemplate.hasKey(key)) {
            return redisTemplate.getExpire(key);
        } else {
            return Long.parseLong(-2 + "");
        }
    }

4.编写Controller测试

@Controller
@ResponseBody
public class CaptchaController {

    @Resource
    private RedisClient redisClient;

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setFont(Captcha.FONT_1);
        String id = UUID.randomUUID().toString();
        response.setHeader("id", id);
        CaptchaUtil.out(specCaptcha, request, response);
        String verCode = specCaptcha.text().toLowerCase();
        redisClient.set(id, verCode);//可设置有效时间,单位为秒
    }

    @PostMapping(value = "/check")
    public boolean check(@RequestBody String info) {
        JSONObject jsonObject = JSON.parseObject(info);
        String id = jsonObject.getString("id");
        String code = jsonObject.getString("code");
        String s = redisClient.get(id).toString();//id
        return code.equalsIgnoreCase(s);
    }
}

访问localhost:8081/captcha 别忘了启动Redis

SpringBoot集成Redis实现验证码的简单案例

这里的id就是存进Redis的键

SpringBoot集成Redis实现验证码的简单案例

我们拿到Redis的键再去请求 localhost:8081/check 验证我们的验证码是否是正确的

SpringBoot集成Redis实现验证码的简单案例

 

总结

到此这篇关于SpringBoot集成Redis实现验证码的简单案例的文章就介绍到这了,更多相关SpringBoot Redis验证码内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_45329211/article/details/119281731