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服務器。(網上安裝啓動教程很多)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章