seate+dubbo分布式系统下Redis工具类

一、maven坐标

<dependency>

        <groupId>org.redisson</groupId>

        <artifactId>redisson-spring-boot-starter</artifactId>

        <version>3.28.0</version>

</dependency>

二、redis工具类

package com.mark.free.common.jwt;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.ScoredEntry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Component
@Slf4j
public class RedisUtils implements ApplicationContextAware {
    private static RedissonClient redissonClient;
    private static RedisTemplate<String, Object> redisTemplate;
    private static RScheduledExecutorService scheduledExecutorService = null;
    private static ExecutorService executorService = Executors.newFixedThreadPool(4);
    private static final Codec STRING_CODE = new StringCodec();
    private static final JsonMapper MAPPER = new JsonMapper();

    @Value("${spring.application.name}")
    private String name;

    @PostConstruct
    public void init() {
        scheduledExecutorService = redissonClient.getExecutorService(name);
        scheduledExecutorService.registerWorkers(WorkerOptions.defaults());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redissonClient = applicationContext.getBean(RedissonClient.class);
        redisTemplate = (RedisTemplate<String, Object>) applicationContext.getBean("redisTemplate");
    }

    /**
     * 获取一个key
     *
     * @param key
     * @return 字符串
     */
    public static String getValue(String key) {
        Object result = redissonClient.getBucket(key, STRING_CODE).get();
        return result == null ? null : result.toString();
    }

    /**
     * 获取一个key,并转化为一个实体类
     *
     * @param key
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> T getValue(String key, Class<T> targetClass) {

        Object result = redissonClient.getBucket(key, STRING_CODE).get();
        try {
            return result == null ? null : JSONObject.parseObject(result.toString(), targetClass);
        } catch (Exception e) {
            log.error("redis数据获取json解析异常", e);
            return (T) result;
        }
    }

    /**
     * 保存一个key
     *
     * @param key
     * @param value
     * @param <T>
     */
    public static <T> void setValue(String key, T value) {
        redissonClient.getBucket(key, STRING_CODE).set(serializableToStr(value));
    }

    /**
     * 保存一个key,并设置有效期
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     * @param <T>
     */
    public static <T> void setValue(String key, T value, long time, TimeUnit unit) {
        redissonClient.getBucket(key, STRING_CODE).set(serializableToStr(value), time, unit);
    }

    /**
     * 序列号值
     *
     * @param value 存入的值
     * @param <T>
     * @return
     */
    private static <T> String serializableToStr(T value) {
        String valueStr = null;
        if (value != null && value instanceof String) {
            valueStr = (String) value;
        } else if (value != null) {
            valueStr = JSONObject.toJSONString(value);
        }
        return valueStr;
    }

    /**
     * 判断是否存在一个key
     *
     * @param key
     * @return
     */
    public static boolean isExists(String key) {
        return redissonClient.getBucket(key, STRING_CODE).isExists();
    }

    /**
     * 删除key
     *
     * @param key
     * @return
     */
    public static boolean delete(String key) {
        return redissonClient.getBucket(key, STRING_CODE).delete();
    }

    /**
     * 获取一个List的key
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> List<T> getList(String key, Class<T> clazz) {
        RList<Object> rList = redissonClient.getList(key);
        List<Object> objectList = rList.readAll();
        if (CollectionUtil.isEmpty(objectList)) {
            return null;
        }
        return Convert.toList(clazz, objectList);
    }

    /**
     * 保存一个value到list的key中
     *
     * @param key        键
     * @param collection 集合数据
     * @param <T>
     * @return
     */
    public static <T> boolean setListAll(String key, Collection<T> collection) {
        return redissonClient.getList(key).addAll(collection);
    }

    /**
     * 保存一个value到list的key中
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean addListValue(String key, T value) {
        return redissonClient.getList(key).add(value);
    }

    /**
     * 将一个list存入一个key中
     *
     * @param key
     * @param list
     * @param <T>
     * @return
     */
    public static <T> boolean setSetList(String key, List<T> list) {
        return redissonClient.getSet(key, STRING_CODE).addAll(list);
    }

    /**
     * 从list中移除一个value
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean removeListValue(String key, T value) {
        return redissonClient.getList(key, STRING_CODE).remove(value);
    }

    /**
     * 判断list中有无此value
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean isExistsForList(String key, T value) {
        return redissonClient.getList(key, STRING_CODE).contains(value);
    }

    /**
     * 获取一个set
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> RSet<T> getSet(String key) {
        return redissonClient.getSet(key, STRING_CODE);
    }

    /**
     * 保存一个value到set中
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean setSetValue(String key, T value) {
        return redissonClient.getSet(key, STRING_CODE).add(value);
    }

    /**
     * 从set移除此value
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean removeSetValue(String key, T value) {
        return redissonClient.getSet(key, STRING_CODE).remove(value);
    }

    /**
     * 查看set中有无此value
     *
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static <T> boolean isExistsForSet(String key, T value) {
        return redissonClient.getSet(key, STRING_CODE).contains(value);
    }

    /**
     * 比较并设置一个value到目标key中
     *
     * @param key
     * @param target
     * @param source
     * @param <T>
     * @return
     */
    public static <T> boolean compareAndSet(String key, T target, T source) {
        return redissonClient.getBucket(key, STRING_CODE).compareAndSet(target, source);
    }


    /**
     * 对一个key设置一个有效期
     *
     * @param key
     * @param time
     * @param unit
     * @return
     */
    public static boolean expire(String key, long time, TimeUnit unit) {
        return redissonClient.getBucket(key, STRING_CODE).expire(time, unit);
    }

    /**
     * 获取一个key的剩余存活时间
     *
     * @param key
     * @return
     */
    public static long remainTimeToLive(String key) {
        return redissonClient.getBucket(key).remainTimeToLive();
    }

    /**
     * 获取一个key的值然后加1
     *
     * @param key
     * @return
     */
    public static long getAndIncrement(String key) {
        return redissonClient.getAtomicLong(key).getAndIncrement();
    }

    /**
     * 获取一个key加1后的值
     *
     * @param key
     * @return
     */
    public static long incrementAndGet(String key) {
        return redissonClient.getAtomicLong(key).incrementAndGet();
    }

    /**
     * 保存一个值到有序集合
     *
     * @param key   有序集合的key
     * @param value 有序集合的值
     * @param score 排序的分数
     * @return 是否成功
     */
    public static boolean setZSet(String key, Object value, Double score) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).add(score, value);
    }

    /**
     * 保存多个值到有序集合
     *
     * @param key      有序集合的key
     * @param valueMap 存入的值和分数
     * @return 是否成功
     */
    public static int setZSet(String key, Map<Object, Double> valueMap) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).addAll(valueMap);
    }

    /**
     * 保存多个值到有序集合
     *
     * @param key     有序集合的key
     * @param pattern 正则
     * @return
     */
    public static String getZSetOne(String key, String pattern) {

        Stream<Object> stream = redissonClient.getScoredSortedSet(key, STRING_CODE).stream(pattern, 1);
        if (stream == null) {
            return null;
        }
        Iterator<Object> iterator = stream.iterator();
        if (!iterator.hasNext()) {
            return null;
        }
        return iterator.next().toString();
    }

    /**
     * 有序集合中是否存在该值
     *
     * @param key   key
     * @param value 值
     * @return
     */
    public static boolean containsZSet(String key, Object value) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).contains(value);
    }

    /**
     * 获取有序集合,分数从高到底排序
     *
     * @param key        有序集合的key
     * @param startIndex 开始索引,从零开始
     * @param endIndex   结束索引,从零开始,比如需要取一个,结束所有就为0
     * @return 是否成功
     */
    public static List<String> getZSetEntryRangeReversed(String key, int startIndex, int endIndex) {
        List<String> keys = new ArrayList<>();
        Collection<ScoredEntry<Object>> scoredEntries = redissonClient.getScoredSortedSet(key, STRING_CODE).entryRangeReversed(startIndex, endIndex);
        for (ScoredEntry<Object> scoredEntry : scoredEntries) {
            keys.add(scoredEntry.getValue().toString());
        }
        return keys;
    }

    /**
     * 获取有序集合值和分数,分数从高到底排序
     *
     * @param key        有序集合的key
     * @param startIndex 开始索引,从零开始
     * @param endIndex   结束索引,从零开始,比如需要取一个,结束所有就为0
     * @return 是否成功
     */
    public static Map<Object, Double> getZSetEntryRangeReversedMap(String key, int startIndex, int endIndex) {
        Map<Object, Double> map = new LinkedHashMap<>();
        Collection<ScoredEntry<Object>> scoredEntries = redissonClient.getScoredSortedSet(key, STRING_CODE).entryRangeReversed(startIndex, endIndex);
        for (ScoredEntry<Object> scoredEntry : scoredEntries) {
            map.put(scoredEntry.getValue(), scoredEntry.getScore());
        }
        return map;
    }

    /**
     * 获取有序序列size
     *
     * @param key 序列key
     * @return
     */
    public static int getZSetSize(String key) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).size();
    }

    /**
     * 删除有序序列的值
     *
     * @param key   序列key
     * @param value 序列的值
     * @return
     */
    public static boolean removeZSetValue(String key, Object value) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).remove(value);
    }


    /**
     * 读取有序集合的所有值
     *
     * @param key 有序集合的key
     * @return
     */
    public static List<String> readAllZSet(String key) {
        Collection<Object> valueList = redissonClient.getScoredSortedSet(key, STRING_CODE).readAll();
        List<String> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(valueList)) {
            valueList.forEach(value -> {
                resultList.add(value.toString());
            });
        }
        return resultList;
    }

    /**
     * 获取有序集合所有的值
     *
     * @param key     有序集合的key
     * @param pattern value正则匹配
     * @return
     */
    public static List<String> streamZSet(String key, String pattern) {
        Stream<Object> stream = redissonClient.getScoredSortedSet(key, STRING_CODE).stream(pattern);
        List<String> resultList = new ArrayList<>();
        if (stream != null) {
            stream.forEach(value -> {
                resultList.add(value.toString());
            });
        }
        return resultList;
    }

    /**
     * 获取有序集合所有的值
     *
     * @param key 有序集合的key
     * @return
     */
    public static List<Object> streamZSet(String key) {
        Stream<Object> stream = redissonClient.getScoredSortedSet(key, STRING_CODE).stream();
        List<Object> resultList = new ArrayList<>();
        if (stream != null) {
            stream.forEach(value -> {
                resultList.add(value.toString());
            });
        }
        return resultList;
    }

    /**
     * 设置hash值
     *
     * @param name  map名称
     * @param key   对应的key
     * @param value 对应的值
     * @return
     */
    public static Object setHashValue(String name, Object key, Object value) {
        return redissonClient.getMap(name, STRING_CODE).put(key, serializableToStr(value));
    }

    /**
     * 设置hash值
     *
     * @param name map名称
     * @param map  插入的键值对
     * @return
     */
    public static Object setHashValueAll(String name, Map<?, ?> map) {
        //处理值
        Map<String, String> cacheMap = new HashMap<>();
        map.keySet().forEach(key -> {
            cacheMap.put(key.toString(), serializableToStr(map.get(key)));
        });
        return redissonClient.getMap(name, STRING_CODE).putAllAsync(cacheMap);
    }

    /**
     * 获取hash中的值
     *
     * @param name 姓名
     * @param key  对应的key
     * @return
     */
    public static <T> T getHashValue(String name, Object key, Class<T> type) {
        Object value = redissonClient.getMap(name, STRING_CODE).get(key);
        try {
            return value == null ? null : MAPPER.readValue(value.toString(), type);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取hash中的值-多key获取
     *
     * @param name 姓名
     * @param keys 对应的key
     * @return
     */
    public static <T> Map<Object, T> getHashValueAll(String name, Set<Object> keys, Class<T> type) {
        Map<Object, Object> map = redissonClient.getMap(name, STRING_CODE).getAll(keys);
        //值转换
        Map<Object, T> resultMap = new HashMap<>();
        map.keySet().forEach(key -> {
            try {
                resultMap.put(key, Convert.convert(type, map.get(key).toString()));
            } catch (Exception e) {
                log.warn("redis获取map值转换异常", e);
            }
        });
        return resultMap;
    }

    /**
     * 获取hash中的值-多key获取
     *
     * @param name 姓名
     * @param keys 对应的key
     * @return
     */
    public static <T> List<T> getHashValueListAll(String name, Set<Object> keys, Class<T> type) {
        Map<Object, Object> map = redissonClient.getMap(name, STRING_CODE).getAll(keys);
        //值转换
        List<T> list = new ArrayList<>();
        map.keySet().forEach(key -> {
            try {
                list.add(MAPPER.readValue(map.get(key).toString(), type));
            } catch (JsonProcessingException e) {
                log.warn("redis获取map值转换异常", e);
            }
        });
        return list;
    }

    /**
     * 移除hash的key
     *
     * @param name map名称
     * @param key  对应的key
     * @return
     */
    public static Object removeHashKey(String name, Object key) {
        return redissonClient.getMap(name, STRING_CODE).remove(key);
    }

    /**
     * 获取hash中所有的值
     *
     * @param name 名称
     * @param type 值类型
     * @param <T>
     * @return
     */
    public static <T> List<T> listAllHash(String name, Class<T> type) {
        Set<Map.Entry<Object, Object>> entrySet = redissonClient.getMap(name, STRING_CODE).entrySet();
        List<T> resultList = new ArrayList<>();
        entrySet.forEach(map -> {
            try {
                resultList.add(MAPPER.readValue(map.getValue().toString(), type));
            } catch (JsonProcessingException e) {
                log.error("获取hash值转换异常", e);
            }
        });
        return resultList;
    }

    /**
     * 获取范围分数的值个数
     *
     * @param key                 有序集合的key
     * @param startScore          开始分数
     * @param startScoreInclusive 是否包含开始分数
     * @param endScore            结束分数
     * @param endScoreInclusive   是否包含结束分数
     * @return
     */
    public static List<String> listZSetRangeReversed(String key, double startScore, boolean startScoreInclusive,
                                                     double endScore, boolean endScoreInclusive, int offset, int count) {
        Collection<ScoredEntry<Object>> scoredEntries = redissonClient.getScoredSortedSet(key, STRING_CODE)
                .entryRangeReversed(startScore, startScoreInclusive, endScore, endScoreInclusive, offset, count);
        List<String> resultList = new ArrayList<>();
        for (ScoredEntry<Object> scoredEntry : scoredEntries) {
            resultList.add(scoredEntry.getValue().toString());
        }
        return resultList;
    }

    /**
     * 获取范围分数的值个数
     *
     * @param key                 有序集合的key
     * @param startScore          开始分数
     * @param startScoreInclusive 是否包含开始分数
     * @param endScore            结束分数
     * @param endScoreInclusive   是否包含结束分数
     * @return
     */
    public static List<String> listZSetRangeReversed(String key, double startScore, boolean startScoreInclusive,
                                                     double endScore, boolean endScoreInclusive) {
        Collection<ScoredEntry<Object>> scoredEntries = redissonClient.getScoredSortedSet(key, STRING_CODE)
                .entryRangeReversed(startScore, startScoreInclusive, endScore, endScoreInclusive);
        List<String> resultList = new ArrayList<>();
        for (ScoredEntry<Object> scoredEntry : scoredEntries) {
            resultList.add(scoredEntry.getValue().toString());
        }
        return resultList;
    }

    /**
     * 删除范围分数的值
     *
     * @param key                 有序集合的key
     * @param startScore          开始分数
     * @param startScoreInclusive 是否包含开始分数
     * @param endScore            结束分数
     * @param endScoreInclusive   是否包含结束分数
     * @return
     */
    public static int removeZSetValue(String key, double startScore, boolean startScoreInclusive, double endScore, boolean endScoreInclusive) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).removeRangeByScore(startScore, startScoreInclusive, endScore, endScoreInclusive);
    }

    /**
     * 批量删除有序集合value
     *
     * @param key       有序集合key
     * @param valueList 需要删除的value
     * @return
     */
    public static boolean removeAllZSetValue(String key, List<Object> valueList) {
        return redissonClient.getScoredSortedSet(key, STRING_CODE).removeAll(valueList);
    }

    /**
     * 设置值,在key不存在的时候
     *
     * @param key      设置的key
     * @param value    设置的值
     * @param timeout  超时时间
     * @param timeUnit 超时时间单位
     * @return
     */
    public static boolean setKeyIfNotExists(String key, String value, long timeout, TimeUnit timeUnit) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit);
    }

    /**
     * 获取key剩余时间【单位:毫秒】
     *
     * @param key
     * @return
     */
    public static long getTtl(String key) {
        return redissonClient.getBucket(key).remainTimeToLive();
    }

    /**
     * key自增
     *
     * @param key
     * @return
     */
    public static Long incr(String key) {
        return redisTemplate.opsForValue().increment(key);
    }

    /**
     * 分布式锁
     */
    public static RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

    /**
     * 锁续期并设置等待时间、过期时间、过期时间类型
     *
     * @param lockKey
     * @param waitTime
     * @param leaseTime
     * @param unit
     * @return
     * @throws InterruptedException
     */
    public static boolean tryLock(String lockKey, long waitTime, long leaseTime,
                                  TimeUnit unit) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock(waitTime, leaseTime, unit);
    }

    public static void unLock(RLock lock) {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    public static void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        //锁定状态,且为当前线程,解锁
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    public static <T> T get(String key, Class<T> clazz) {
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        }
        return Convert.convert(clazz, obj);
    }

    public static Boolean deleteKey(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 是否存在key
     *
     * @param key
     * @return
     */
    public static Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值