RedisUtil.java 5.15 KB
package com.idss.vulsync.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询键
     *
     * @param key 键 支持ant
     * @return Set
     */
    public Set<String> keys(String key) {
        return redisTemplate.keys(key);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            boolean delete;
            if (key.length == 1) {
                delete = redisTemplate.delete(key[0]);
            } else {
                delete = 0L < redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
            log.info("@@@@@ del处理key值为{},结果delete信息为:{}", JSON.toJSONString(key), delete);
        }
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     */
    public void set(String key, Object value, TimeUnit timeUnit, long time) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, timeUnit);
        } else {
            set(key, value);
        }
    }

    /**
     * 普通缓存放入并设置时间(带返回值)
     *
     * @param key      key
     * @param value    value
     * @param timeUnit timeUnit
     * @param time     time
     * @return boolean
     */
    public boolean setIfAbsent(String key, Object value, TimeUnit timeUnit, long time) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, time, timeUnit);
    }

    /**
     * 加锁(单次获取)
     *
     * @param lockKey    lockKey
     * @param lockValue  lockValue
     * @param expireTime expireTime
     * @return boolean
     */
    public boolean tryLockSingle(String lockKey, String lockValue, long expireTime) {
        //SET命令返回true时,则证明加锁成功,设置超时时间间隔,默认超时时间单位为分钟
        return setIfAbsent(lockKey, lockValue, TimeUnit.MINUTES, expireTime);
    }

    /**
     * 加锁,无阻塞
     *
     * @param lockKey    lockKey
     * @param lockValue  lockValue
     * @param expireTime expireTime
     * @return boolean
     */
    public boolean tryLock(String lockKey, String lockValue, long expireTime) throws InterruptedException {
        while (true) {
            String threadName = Thread.currentThread().getName();
            //SET命令返回true时,则证明加锁成功,设置超时时间间隔,默认超时时间单位为分钟
            boolean isExistFlag = setIfAbsent(lockKey, lockValue, TimeUnit.MINUTES, expireTime);
            if (isExistFlag) {
                log.info("@@@@@ 进程ID为[{}],加锁成功!", threadName);
                return true;
            } else {
                log.info("@@@@@ 进程ID为[{}],加锁失败!500毫秒后继续尝试加锁!", threadName);
                //睡100毫秒继续尝试加锁
                TimeUnit.MILLISECONDS.sleep(500);
            }
        }
    }

    /**
     * 解锁处理
     *
     * @param lockKey   lockKey
     * @param lockValue lockValue
     */
    public void unLock(String lockKey, String lockValue) {
        String threadName = Thread.currentThread().getName();
        try {
            log.info("@@@@@ 进程ID为[{}]准备unLock处理lockKey值为:{},lockValue值为:{}", threadName, lockKey, lockValue);
            String currentValue = (String) get(lockKey);
            log.info("@@@@@ 进程ID为[{}]准备unLock处理currentValue值为:{}", threadName, currentValue);
            if (StringUtils.isNotEmpty(currentValue) && currentValue.equals(lockValue)) {
                del(lockKey);
            }
        } catch (Exception e) {
            log.error("@@@@@ 进程ID为[{}],unLock处理失败!异常信息为:{}", threadName, e.getMessage(), e);
        }
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<String, String> getHashMap(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
}