A simple example of SpringBoot+Redis integration captcha

A simple record of a learning process

Download and install Redis

Here is not much to say, download and install Redis, it is best to install Redis Desktop Manager together, visual look comfortable.

Second, the code part

1. Introducing Redis dependencies, here MY SpringBoot version is 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>
Copy the code

Captcha dependency

<dependency>
       <groupId>com.github.whvcse</groupId>
       <artifactId>easy-captcha</artifactId>
       <version>1.6.2</version>
</dependency>
Copy the code

Here is a simple example of yML configuration. You can configure it based on your own service requirements

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

Copy the code

2. Write 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);
        // serialize key and value
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        returnredisTemplate; }}Copy the code

3. Write RedisUtils

@Component
public class RedisClient {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /* * @className RedisClient * @desc TODO Set cache (no time limit) * @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 Set cache (time limit, in seconds) * @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 deletes the cache and returns whether the cache was deleted successfully * @date 2021-07-24 16:11 * @version 1.0 */
    public boolean delete(String key) {
        redisTemplate.delete(key);
        // Delete failed if the key still exists
        if (redisTemplate.hasKey(key)) {
            return false;
            // The deletion succeeds if it does not exist
        } else {
            return true; }}/* * @className RedisClient * @desc TODO retrieve cache * @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 Obtain expiration time (-2: invalid / -1: no time limit) * @date 2021-07-24 16:15 * @version 1.0 */
    public long getExpire(String key) {
        // Check whether it exists
        if (redisTemplate.hasKey(key)) {
            return redisTemplate.getExpire(key);
        } else {
            return Long.parseLong(-2 + ""); }}Copy the code

4. Write Controller tests

@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);// The validity period can be set in seconds
    }

    @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
        returncode.equalsIgnoreCase(s); }}Copy the code

Access localhost:8081/captcha and don’t forget to start Redis

The ID here is the key stored in Redis

We get the Redis key and ask localhost:8081/check to verify that our verification code is correct

Here is the end, small white a simple verification code integration ~, there are wrong places welcome to point out