说明:这里只是代码记录,不讲原理。
需求:业务上需要记录一些数据,60秒过期,所以想到放在redis里面,但是无论set还是hash都无法做到对单个item做过期设置。所以只能做普通的key-value存储,在key上面做约束,前缀一致就行。这就需要做redis key模糊查找。
以下是实现:
public Set<String> matchKeys(String prefix) {
if (StringUtils.isEmpty(prefix)) {
return new HashSet<>();
}
Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keysTmp = new HashSet<>();
ScanOptions scanOptions = ScanOptions.scanOptions().match(prefix + "*")
.count(100)
.build();
Cursor<byte[]> cursor = connection.scan(scanOptions);
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
return keysTmp;
});
return keys;
}