在游标里写逻辑,控制删除哪些key。
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;
@Service
public class RedisKeyDeletionService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void deleteKeysEndingWith(String pattern,int flag) {
// 构造匹配模式
final String KEY_PATTERN = "*" + pattern;
Cursor<byte[]> cursor = redisTemplate.execute(new RedisCallback<Cursor<byte[]>>() {
@Override
public Cursor<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
return connection.scan(ScanOptions.scanOptions().match(KEY_PATTERN).count(100).build());
}
});
try {
while (cursor.hasNext()) {
byte[] keyBytes = cursor.next();
String key = new String(keyBytes);
if(key.endsWith(":::1"+pattern) && flag ==0){//redis内置条件和外置条件
continue;
}
// 再次检查以确保匹配模式
if (key.endsWith(pattern)) {
redisTemplate.delete(key);
}
}
} finally {
cursor.close(); // 关闭游标
}
}
// 示例用法
public static void main(String[] args) {
// 这里只是一个示例,实际应用中你应该在Spring容器中运行并注入RedisTemplate
RedisKeyDeletionService service = new RedisKeyDeletionService();
// 假设你已经有一个配置好的RedisTemplate实例,这里我们只是模拟调用
// ... 注入或配置 redisTemplate ...
service.deleteKeysEndingWith("070401:::PCT");
}
}