spring-data-redis使用小记

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")));


你可能感兴趣的:(spring-data-redis使用小记)