springboot 生成验证码 并存入 redis

一、注入依赖

1、验证码依赖  

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

2、redis依赖

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

二、配置yaml文件

spring:
  data:
    redis:
      host: <hostname>
      port: <port>
      database: 0

三、实现

1、验证码类

package com.wt.lease.web.admin.vo.login;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@Schema(description = "图像验证码")
@AllArgsConstructor
public class CaptchaVo {

    @Schema(description="验证码图片信息")
    private String image;

    @Schema(description="验证码key")
    private String key;
}

2、生成并保存redis

 

package com.wt.lease.web.admin.service.impl;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.wt.lease.web.admin.service.LoginService;
import com.wt.lease.web.admin.vo.login.CaptchaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public CaptchaVo getCaptcha() {
        // 返回验证码的 byte
        // 设置验证码尺寸和长度
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 设置验证码类型
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        // 验证码小写
        String code = specCaptcha.text().toLowerCase();

        // 存入redis 要有key 和 value(code)
        // 配置 key
        String key = String.valueOf(UUID.randomUUID());
        String image = specCaptcha.toBase64();
        // 存入 redis, 并设置过期时间
        redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);

        return new  CaptchaVo(image, key);
    }
}

 

posted @ 2025-05-15 20:42  市丸银  阅读(71)  评论(0)    收藏  举报