根据key判断值的类型
public DataType typeOfKey(String key) {
return key == null ? null : redisTemplate.type(key);
}
根据key删除
public Boolean delete(String key) {
return key != null && Boolean.TRUE.equals(redisTemplate.delete(key));
}
将当前数据库的key移动到指定dbIndex中
public boolean move(String key, int dbIndex) {
try {
return redisTemplate.move(key, dbIndex);
} catch (NullPointerException e) {
log.error("空指针异常");
return false;
}
}
模糊查询
public Set<String> scan(String pattern) {
ScanOptions options = ScanOptions.scanOptions()
.count(3000)
.match(pattern).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
Cursor<String> cursor = redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
Set<String> result = new HashSet<>();
while (cursor.hasNext()) {
result.add(cursor.next());
}
cursor.close();
return result;
}
随机生成key
public String randomKey() {
return redisTemplate.randomKey();
}
实现db索引切换
public void selectDb(int databaseIndex) {
redisTemplate.getConnectionFactory().getConnection().select(databaseIndex);
}
删除多个key
public int del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
boolean isDel = redisTemplate.delete(key[0]);
return isDel ? 1 : 0;
} else {
return Math.toIntExact(redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key))
);
}
} else {
return 0;
}
}
判断是否存在key
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
指定缓存失效时间
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
根据key获取过期时间
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
删除key的过期时间
public Boolean persist(String key) {
return redisTemplate.persist(key);
}