您的位置:首页 > 数据库 > Redis

spring-data-redis的使用优化

2016-04-13 16:57 609 查看
1、批量删除keys

/**
批量提交
* @param keys
* @return
*/
public long del(final String... keys) throws CacheException {
return (long) redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
byte[][] bytes = new byte[keys.length][];
int index = 0;
for(String key: keys){
bytes[index++] = stringSerializer.serialize(key);
}
return connection.del(bytes);
}
});
}
/*循环多次提交(不建议使用)
public long del(final String... keys) throws CacheException {
return (long) redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
long result = 0;
for (int i = 0; i < keys.length; i++) {
result += connection.del(redisTemplate.getStringSerializer().serialize(keys[i]));
}
return result;
}
});
}*/


2、遍历keys

/**
* @param pattern
* @return
*/
public Set<String> keys(final String pattern) throws CacheException {
return redisTemplate.execute(new RedisCallback<Set<String>>() {
public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
Set<String> keys = new HashSet<String>();
Set<byte[]> set = connection.keys(stringSerializer.serialize(pattern));
for (Iterator<byte[]> iterator = set.iterator(); iterator.hasNext();){
byte[] data = iterator.next();
keys.add(stringSerializer.deserialize(data));
}
return keys;
}
});
}
// 注意使用redisTemplate的方法直接调用需要关注序列化规则!
Set<byte[]> keys = redisTemplate.keys("*");
// Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes(Charset.forName("UTF8")));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: