Redis生成验证码

一、首先引入Redis依赖的jar包并添加配置


//添加Ridis库
compile('org.springframework.boot:spring-boot-starter-redis:1.3.8.RELEASE')
//添加第三方验证
compile('cn.apiclub.tool:simplecaptcha:1.2.2')
redis:
    database: 4
    host: 112.74.112.251
    port: 6379
    password:
    pool:
      max-active: 8
      max-wait: -1
      max-idle: 8
      min-idle: 0



二、创建Redis的工厂类


package com.nsu.Bean;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by Administrator on 2017/3/10 0010.
 */
public class RedisConfig {

    @Bean
    JedisConnectionFactory jedisConnectionFactory(){
        return new JedisConnectionFactory();
    }

    @Bean
    RedisTemplate redisTemplate (RedisConnectionFactory factory){
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }

}




三、生成验证码
import cn.apiclub.captcha.Captcha;
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;
import cn.apiclub.captcha.gimpy.DropShadowGimpyRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/3/10 0010.
 */
@Controller
public class captChaModule {

    private static int captChaExpires = 3 * 60;
    private static int captChaW = 60*3;
    private static int cpaChaH = 60;
    private static String uuid;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/cap",method = RequestMethod.GET)
    public @ResponseBody byte[] getCaptCha(HttpSession session){
//        判断验证码是否存在,存在的话便根据Key清除验证码缓存
        if(session.getAttribute("UUID")!=null){
            uuid = session.getAttribute("UUID").toString().trim();
            redisTemplate.delete(uuid);
        }
//        生成验证码的key
        uuid = UUID.randomUUID().toString().trim();

        /*设置背景的渐进*/
        GradiatedBackgroundProducer gbp=new GradiatedBackgroundProducer();
        gbp.setFromColor(Color.DARK_GRAY);
        gbp.setToColor(Color.PINK);
        //无渐进效果,只是填充背景颜色
//         FlatColorBackgroundProducer  fbp=new FlatColorBackgroundProducer(Color.pink);
        //加入网纹
//         SquigglesBackgroundProducer  sbp=new SquigglesBackgroundProducer();


        /*字体设置*/
        // 字体边框齿轮效果 默认是3
//        gimp(new BlockGimpyRenderer(1));
        //波纹渲染 相当于加粗
//         gimp(new RippleGimpyRenderer());
        //修剪--一般不会用
//         gimp(new ShearGimpyRenderer(Color.red));
        //加网--第一个参数是横线颜色,第二个参数是竖线颜色
//         gimp(new FishEyeGimpyRenderer(Color.red,Color.yellow));
        //加入阴影效果 默认3,75
//         gimp(new DropShadowGimpyRenderer());


        /*.
        *.Builder为设置验证码的长宽
        *.addBackground()
        *.addText()生成5个默认的数字字符
        * .addBackground()添加背景
        * .gimp()字体设置
        * */
        Captcha captcha = new Captcha.Builder(captChaW,cpaChaH).addText()
                .addBackground(gbp)
                .gimp(new DropShadowGimpyRenderer()).build();
//        将图片缓存在redisTemplate(第一个参数为验证码的key,第二个为验证码的value,第三个为缓存的时间,第四个为缓存时间单位:秒)
        redisTemplate.opsForValue().set(uuid,captcha.getAnswer(),captChaExpires, TimeUnit.SECONDS);
        System.out.println("UUID"+uuid+"PASSWORD"+captcha.getAnswer());
        session.setAttribute("UUID",uuid);

/*        Cookie cookie = new Cookie("UUID",uuid);
        response.addCookie(cookie);*/

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            ImageIO.write(captcha.getImage(), "png", bao);
            return bao.toByteArray();
        }catch (Exception e){
            return null;
        }
    }
}


四、前端调用,点击更换验证码

 
   

五、注意
要下载redis缓存服务器,并且每次程序运行前,要开启redis服务器。(网上安装启动教程很多)


你可能感兴趣的:(Redis生成验证码)