商品 批量操作

This commit is contained in:
2026-05-06 11:10:23 +08:00
parent 962e6d7a0c
commit d9d95da453
5 changed files with 129 additions and 5 deletions

View File

@@ -5,7 +5,10 @@ import com.alibaba.fastjson2.JSONWriter;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@@ -52,6 +55,34 @@ public class RedisService {
return redisTemplate.delete(keys);
}
/**
* 删除某前缀Key
* @param prefix
*/
public void deleteKeysByPrefixSafe(String prefix) {
// 拼接匹配规则:前缀 + * → 比如传入 user → 匹配 user*
String pattern = prefix + "*";
// redisTemplate.execute使用 Redis 底层连接执行原生命令(性能更高)
redisTemplate.execute((RedisCallback<Void>) connection -> {
// try-with-resources自动关闭游标避免资源泄漏
try (Cursor<byte[]> cursor = connection.scan(
// SCAN 配置匹配规则、每次扫描1000条
ScanOptions.scanOptions().match(pattern).count(1000).build()
)) {
// 迭代遍历扫描到的所有 key
while (cursor.hasNext()) {
// 删除当前遍历到的 key
connection.del(cursor.next());
}
} catch (Exception e) {
// 异常捕获打印,避免删除失败导致程序报错
e.printStackTrace();
}
return null;
});
}
/**
* 指定缓存失效时间
*