陈昶聿
3 天以前 d7e3192804fca756d881af360ffd5eea157ef9ad
ruoyi-common/src/main/java/com/ruoyi/common/core/redis/RedisCache.java
@@ -4,7 +4,9 @@
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.dao.DataAccessException;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
@@ -14,6 +16,7 @@
 *
 * @author ruoyi
 **/
@Slf4j
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
@@ -44,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);
    }
    /**
@@ -289,9 +306,25 @@
     * @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;
        // 先判断 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;
        }
    }
    /**