liusheng
2025-02-21 86e7cce6159d6d74bcc636327939ec9ea8d3009d
ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java
@@ -1,17 +1,11 @@
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 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.data.redis.core.*;
import org.springframework.stereotype.Component;
/**
@@ -19,7 +13,7 @@
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked" , "rawtypes"})
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
    @Autowired
@@ -127,10 +121,46 @@
     * @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) {
        // 获取 ListOperations 对象,用于操作 Redis List
        ListOperations<String, String> listOps = redisTemplate.opsForList();
        // 获取现有的 cache-0 列表中的所有值
        List<String> existingValues = listOps.range(cacheKey, 0, -1);
        // 过滤出不在 Redis 列表中的值
        List<String> newValues = list.stream().filter(value -> !existingValues.contains(value)).collect(Collectors.toList());
        // 将新的值添加到 Redis 列表的左侧
        if (!newValues.isEmpty()) {
            listOps.leftPushAll(cacheKey, newValues);
        }
    }
    /**
     * 获得缓存的list对象
@@ -245,6 +275,19 @@
    }
    /**
     * 删除缓存LIST中的某个数据
     *
     * @param key           Redis键
     * @param valueToRemove 需要删除的值
     * @return Long 大于0表示删除了几个,等于0表示没有删除,小于0表示在执行删除操作时发生了错误
     */
    public Long removeElementFromList(String key, String valueToRemove) {
        ListOperations<String, String> listOps = redisTemplate.opsForList();
        Long remove = listOps.remove(key, 0, valueToRemove);
        return remove;
    }
    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀