| | |
| | | import java.util.*; |
| | | import java.util.concurrent.TimeUnit; |
| | | 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.data.redis.core.script.DefaultRedisScript; |
| | | import org.springframework.data.redis.core.script.RedisScript; |
| | | import org.springframework.stereotype.Component; |
| | |
| | | RedisScript<Long> script = new DefaultRedisScript<>(luaScript, Long.class); |
| | | return redisTemplate.execute(script, Collections.singletonList(key), value); |
| | | } |
| | | |
| | | /** |
| | | * 从 List 中移除所有 value 包含指定关键字的元素 |
| | | * @param key Redis key |
| | | * @param pattern 要匹配的关键字(如 "abc" 会匹配包含 "abc" 的所有元素) |
| | | * @return 移除的数量 |
| | | */ |
| | | public Long removeByPattern(String key, String pattern) { |
| | | ListOperations<String, String> listOps = redisTemplate.opsForList(); |
| | | |
| | | // 1. 获取 List 长度 |
| | | Long size = listOps.size(key); |
| | | if (size == null || size == 0) { |
| | | return 0L; |
| | | } |
| | | |
| | | // 2. 获取整个 List(小数据量可用,大数据量要优化) |
| | | List<String> allValues = listOps.range(key, 0, -1); |
| | | if (allValues == null || allValues.isEmpty()) { |
| | | return 0L; |
| | | } |
| | | |
| | | // 3. 找到匹配的元素并记录位置(从后往前删除,避免索引变化) |
| | | long removedCount = 0; |
| | | for (int i = allValues.size() - 1; i >= 0; i--) { |
| | | String value = allValues.get(i); |
| | | if (value != null && value.contains(pattern)) { |
| | | // 使用 LREM 命令删除(从头部开始删除,count=1 表示只删一个) |
| | | Long result = listOps.remove(key, 1, value); |
| | | if (result != null && result > 0) { |
| | | removedCount++; |
| | | } |
| | | } |
| | | } |
| | | |
| | | return removedCount; |
| | | } |
| | | /** |
| | | * 缓存Set |
| | | * |