一.Result工具类封装一个统一返回结果对象后面controller里可以直接返回“成功”或“失败”的数据。public class Result extends HashMapString,Object { public static Result ok(){ Result result new Result(); result.put(code, 200); result.put(msg, 操作成功); return result; } public static Result error(String msg){ Result result new Result(); result.put(code, 500); result.put(msg, msg); return result; } Override public Result put(String key, Object value) { super.put(key, value); return this; } }二.接口代码Controller public class LoginController { Autowired private StringRedisTemplate stringRedisTemplate; GetMapping(/captcha) ResponseBody public Result getCaptcha() { //1.借助第三方工具类(Hutool)生成验证码的图片 //用 Hutool 创建验证码对象。前两个参数是图片宽高第三个是验证码字符数第四个是干扰线数量。 LineCaptcha lineCaptcha CaptchaUtil.createLineCaptcha(120, 40, 4, 20); //2.拿到图片中验证码的值 String code lineCaptcha.getCode(); // 3.生成uuid作为这次验证码的唯一标识 //给当前这张验证码生成一个唯一编号。前端登录时会把用户输入的验证码和这个 uuid 一起传回来后端再去 Redis 里查对应验证码。 String uuid UUID.randomUUID().toString().replace(-, ); // 4. 把验证码存到 redis String redisKey captcha: uuid; //设置验证码过期时间 stringRedisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES); // 5. 获取 base64 图片字符串 //把图片转成前端可直接显示的base64形式前端直接放到 img 的 src 里就能显示。 String imageBase64 data:image/png;base64, lineCaptcha.getImageBase64(); // 6. 返回给前端 //这行代码先执行new Result,得到内层对象,记作dataResult:{ uuid: uuid, captcha: imageBase64,code: code} //再执行code: code得到外层对象,记作Result:{code: 200,msg: 操作成功} //最后执行result.put(data, dataResult),于是变成{code: 200,msg: 操作成功, data: {uuid: uuid,captcha: imageBase64, code: code}} return Result.ok()//对应工具类里的public static Result ok(){........} .put(data, new Result().put(uuid, uuid).put(captcha, imageBase64).put(code, code));//先new一个Result对象然后往里面放三个键值对uuid,captcha,code } }二.在redis中验证1.选择验证码存入的redis库select 12.查keykeys captcha:*结果为captcha:a0dab01b80974615b0a4c9f801f55d863.通过 key 查值get captcha:a0dab01b80974615b0a4c9f801f55d86结果就是生成的验证码4.查看过期时间ttl captcha:a0dab01b80974615b0a4c9f801f55d86结果是一个大于零的整数这就是过期时间