陈昶聿
3 天以前 d7e3192804fca756d881af360ffd5eea157ef9ad
ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java
@@ -1,17 +1,14 @@
package com.ruoyi.common.core.redis;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
/**
@@ -19,7 +16,8 @@
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked" , "rawtypes"})
@Slf4j
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
    @Autowired
@@ -35,6 +33,10 @@
        redisTemplate.opsForValue().set(key, value);
    }
    public <T> void setCacheList(final String key, final List<T> values) {
        redisTemplate.opsForList().rightPushAll(key, values);
    }
    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
@@ -45,6 +47,20 @@
     */
    public <T> void setCacheObject(final String key, final T value, final long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }
    /**
     * 缓存对象,仅当 key 不存在时才写入(原子操作),用于幂等互斥标记
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     * @return true=本次写入成功(之前不存在);false=key 已存在,未写入
     */
    public <T> boolean setCacheObjectIfAbsent(final String key, final T value, final long timeout, final TimeUnit timeUnit) {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit);
        return Boolean.TRUE.equals(success);
    }
    /**
@@ -127,10 +143,48 @@
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
    public <T> long setCacheListRight(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }
    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据(这里如果新增的话,是往头部新增)
     * @return 缓存的对象
     */
    public <T> long setCacheListLeft(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().leftPushAll(key, dataList);
        return count == null ? 0 : count;
    }
    /**
     * 缓存List数据
     *
     * @param cacheKey 缓存的键值
     * @param list     待缓存的List数据(这里如果新增的话,是往头部新增)并去重
     * @return 缓存的对象
     */
    public void setCacheListLeftAndDistinct(String cacheKey, List<String> list) {
        // 检查 key 类型
        DataType keyType = redisTemplate.type(cacheKey);
        if (keyType != DataType.NONE && keyType != DataType.LIST) {
            // 如果已经存在但不是 list 类型,删除它(或直接抛异常也可)
            redisTemplate.delete(cacheKey);
        }
        ListOperations<String, String> listOps = redisTemplate.opsForList();
        List<String> existingValues = listOps.range(cacheKey, 0, -1);
        List<String> newValues = list.stream().filter(value -> !existingValues.contains(value)).collect(Collectors.toList());
        if (!newValues.isEmpty()) {
            listOps.leftPushAll(cacheKey, newValues);
        }
    }
    /**
     * 获得缓存的list对象
@@ -245,6 +299,35 @@
    }
    /**
     * 删除缓存LIST中的某个数据
     *
     * @param key           Redis键
     * @param valueToRemove 需要删除的值
     * @return Long 大于0表示删除了几个,等于0表示没有删除,小于0表示在执行删除操作时发生了错误
     */
    public Long removeElementFromList(String key, String valueToRemove) {
        // 先判断 key 的类型,避免 key 被其它业务/旧版本代码写成了 String、Hash 等非 List 类型时抛 WRONGTYPE
        DataType keyType = redisTemplate.type(key);
        if (keyType == DataType.NONE) {
            return 0L;
        }
        if (keyType != DataType.LIST) {
            // 该 key 本身是作为队列使用的,类型不对说明是脏数据,直接删除,等下次写入时重新创建为 List
            log.warn("Redis key [{}] 的类型为 {},不是 List,已删除该脏数据,避免 WRONGTYPE 异常", key, keyType);
            redisTemplate.delete(key);
            return 0L;
        }
        try {
            Long remove = redisTemplate.opsForList().remove(key, 0, valueToRemove);
            return remove == null ? 0L : remove;
        } catch (DataAccessException e) {
            // 类型检查和删除之间 key 被其它应用改写为其它类型等极端情况兜底,缓存清理失败不应影响主业务流程
            log.warn("从 Redis List [{}] 移除元素 [{}] 失败:{}", key, valueToRemove, e.getMessage());
            return 0L;
        }
    }
    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
@@ -253,4 +336,27 @@
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
    /**
     * 获取当前key值的数量
     * @param key
     * @return
     */
    public Long getListSize(String key) {
        // 检查 key 类型
        DataType keyType = redisTemplate.type(key);
        // 如果 key 不存在,返回 0
        if (keyType == DataType.NONE) {
            return 0L;
        }
        // 如果不是 List 类型,删除它并返回 0(防止 WRONGTYPE 错误)
        if (keyType != DataType.LIST) {
            redisTemplate.delete(key);
            return 0L;
        }
        return redisTemplate.opsForList().size(key);
    }
}