| | |
| | | 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; |
| | |
| | | * |
| | | * @author ruoyi |
| | | **/ |
| | | @Slf4j |
| | | @SuppressWarnings(value = {"unchecked", "rawtypes"}) |
| | | @Component |
| | | public class RedisCache { |
| | |
| | | * @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; |
| | | } |
| | | } |
| | | |
| | | /** |