Java后台生成验证码

    @RequestLimit(count = 60, time = 60)
    @RequestMapping(value = "/captcha", method = {RequestMethod.GET})
    public ResponseEntity captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("### 刷新验证码");
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为30分钟
        redisUtil.set(key, verCode, 30L, TimeUnit.MINUTES);
        // 将key和base64返回给前端
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaImage(specCaptcha.toBase64());
        captchaVO.setCaptchaKey(key);
        log.info("### 刷新验证码:{}, {}", key, verCode);

        return ResponseEntity.ok().body(captchaVO);
    }
package com.**.**.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public void remove(String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    public void removePattern(String pattern) {
        Set<Serializable> keys = this.redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            this.redisTemplate.delete(keys);
        }
    }

    public void remove(String key) {
        if (exists(key)) {
            this.redisTemplate.delete(key);
        }
    }

    public boolean exists(String key) {
        return this.redisTemplate.hasKey(key).booleanValue();
    }

    public <T> T get(String key) {
        T result = null;
        ValueOperations<Serializable, T> operations = this.redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    public <T> boolean set(String key, T value) {
        boolean result = false;
        ValueOperations<Serializable, T> operations = this.redisTemplate.opsForValue();
        operations.set(key, value);
        result = true;
        return result;
    }

    /**
     * 只适用于key对应的值不再更新的问题,如果遇到包含生命周期的值需要更新的情景就不适用了,因为set 方法会丢失该key的生存时间,变成永久有效的
     * @param key
     * @param value
     * @param expireTime 单位秒
     * @param <T>
     * @return
     */
    public <T> boolean set(String key, T value, Long expireTime) {
        boolean result = false;
        ValueOperations<Serializable, T> operations = this.redisTemplate.opsForValue();
        operations.set(key, value);
        this.redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        result = true;
        return result;
    }

    /**
     *
     * 只适用于key对应的值不再更新的问题,如果遇到包含生命周期的值需要更新的情景就不适用了,因为set 方法会丢失该key的生存时间,变成永久有效的
     * @param key
     * @param value
     * @param expireTime
     * @param unit
     * @param <T>
     * @return
     */
    public <T> boolean set(String key, T value, Long expireTime, final TimeUnit unit) {
        boolean result = false;
        ValueOperations<Serializable, T> operations = this.redisTemplate.opsForValue();
        operations.set(key, value);
        this.redisTemplate.expire(key, expireTime, unit);
        result = true;
        return result;
    }

    public <T> T getHash(String hashName, String key) {
        T result = null;
        HashOperations<Serializable, Serializable, T> operations = this.redisTemplate.opsForHash();
        result = operations.get(hashName, key);
        return result;
    }

    public <T> void setHash(String hashName, String key, T value) {
        redisTemplate.opsForHash().put(hashName, key, value);
    }


    /**
     * 只适用于key对应的值不再更新的问题,如果遇到包含生命周期的值需要更新的情景就不适用了,因为set 方法会丢失该key的生存时间,变成永久有效的
     * @param key
     * @param expireTime
     */
    public Boolean expire(String key, Long expireTime) {
        return this.redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 设置分布式锁
     * @param key
     * @param value
     * @return
     */
    public synchronized Boolean setNX(final String key, final String value) throws Exception{
        Object obj = null;
        try {
            obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
                StringRedisSerializer serializer = new StringRedisSerializer();
                Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
                connection.close();
                return success;
            });
        } catch (Exception e) {
            log.error("setNX com.strawhat.redis error, key : {} - {}", key,e);
            throw e;
        }
        return obj != null ? (Boolean) obj : false;
    }

    /**
     * 设置分布式锁,超时间单位秒
     * @param key
     * @param value
     * @return
     */
    public synchronized Boolean setNX(final String key, final String value,long timeOut) throws Exception {
        boolean b = this.setNX(key,value);
        redisTemplate.expire(key,timeOut,TimeUnit.SECONDS);
        return b;
    }

    /**
     * 删除锁
     * @param key
     * @return
     */
    public void unlock(final String key) {
        redisTemplate.delete(key);
    }
}

 

posted on 2019-11-07 15:11  以启山林  阅读(1044)  评论(0编辑  收藏  举报

导航