1. 程式人生 > 其它 >SpringBoot+Redis 整合驗證碼的簡單案例

SpringBoot+Redis 整合驗證碼的簡單案例


一次學習過程中簡單的記錄

一、下載安裝Redis

這裡就不多說了,下載安裝好Redis,最好是把Redis Desktop Manager一起安裝了,視覺化看的舒服一點。

二、程式碼部分

1.引入庫,配置yml

引入Redis依賴,這裡我的springboot版本是2.4.2

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-pool2</artifactId>
       <version>2.10.0</version>
</dependency>

補充一下,這個驗證碼的依賴

<dependency>
       <groupId>com.github.whvcse</groupId>
       <artifactId>easy-captcha</artifactId>
       <version>1.6.2</version>
</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


這裡的id就是存進Redis的鍵


我們拿到Redis的鍵再去請求 localhost:8081/check 驗證我們的驗證碼是否是正確的


總結

到這裡就結束啦,一次簡單驗證碼的整合~