feat: 新增CaptchaService实现类
This commit is contained in:
父節點
42de3bd79c
當前提交
04f1bb339e
@ -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<String, String> 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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user