springboot生成验证码,保存在cache中

1、maven依赖

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>

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

接口代码

/**
     * Local Cache  5分钟过期
     */
    Cache<String, String> localCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build();

    
    /**
     * 生成验证码
     * @param response
     * @param uuid
     * @throws IOException
     */
    @GetMapping("captcha")
    public void captcha(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());
        //保存到缓存
        localCache.put(uuid, captcha.text());
    }

    /**
     * 校验验证码
     * @param uuid
     * @param captcha
     * @return
     */
    @PostMapping("validateCaptcha")
    public Boolean validateCaptcha(String uuid, String captcha) {
    	//获取缓存中的验证码
        String cacheCaptcha = localCache.getIfPresent(uuid);
        //删除验证码
        if(cacheCaptcha != null){
            localCache.invalidate(uuid);
        }
        //效验成功
        if(captcha.equalsIgnoreCase(cacheCaptcha)){
            return true;
        }else {
            return false;
        }
    }

你可能感兴趣的:(java,验证码,登录,缓存)