From 04f1bb339e69dcff45b9431850f961f5bbbaae61 Mon Sep 17 00:00:00 2001 From: weihongyang <1075331873@qq.com> Date: Thu, 23 Jun 2022 13:54:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9ECaptchaService?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/CaptchaServiceImpl.java | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 ym-admin/src/main/java/com/cnbm/admin/service/impl/CaptchaServiceImpl.java diff --git a/ym-admin/src/main/java/com/cnbm/admin/service/impl/CaptchaServiceImpl.java b/ym-admin/src/main/java/com/cnbm/admin/service/impl/CaptchaServiceImpl.java new file mode 100644 index 0000000..ed12f51 --- /dev/null +++ b/ym-admin/src/main/java/com/cnbm/admin/service/impl/CaptchaServiceImpl.java @@ -0,0 +1,77 @@ +package com.cnbm.admin.service.impl; + +import com.cnbm.admin.service.CaptchaService; +import com.cnbm.common.redis.RedisKeys; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.wf.captcha.SpecCaptcha; +import com.wf.captcha.base.Captcha; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * @Author weihongyang + * @Date 2022/6/23 12:29 PM + * @Version 1.0 + */ +@Service +public class CaptchaServiceImpl implements CaptchaService { + @Autowired + private RedisTemplate redisTemplate; + + /** + * Local Cache 5分钟过期 + */ + Cache localCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build(); + + @Override + public void create(HttpServletResponse response, String uuid) throws IOException { + response.setContentType("image/gif"); + response.setHeader("Pragma", "No-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + + //生成验证码 + SpecCaptcha captcha = new SpecCaptcha(150, 40); + captcha.setLen(5); + captcha.setCharType(Captcha.TYPE_DEFAULT); + captcha.out(response.getOutputStream()); + + //保存到缓存 + setCache(uuid, captcha.text()); + } + + @Override + public boolean validate(String uuid, String code) { + //获取验证码 + String captcha = getCache(uuid); + + //效验成功 + if(code.equalsIgnoreCase(captcha)){ + return true; + } + + return false; + } + + private void setCache(String key, String value){ + key = RedisKeys.getCaptchaKey(key); + redisTemplate.opsForValue().set(key, value, 300,TimeUnit.SECONDS); + } + + private String getCache(String key){ + key = RedisKeys.getCaptchaKey(key); + String captcha = (String)redisTemplate.opsForValue().get(key); + //删除验证码 + if(captcha != null){ + redisTemplate.delete(key); + } + return captcha; + } +}