批量查询有一种可以像第一张图一样的根据集合key获取集合value的形式,也可以打开通道,批量的进行redis的操作,然后再关闭通道也是一样的道理,就是减少socket的创建开销。


二十八、redis的批量查询_ide image.png

/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.RedisCallback)
*/
@Override
public List<Object> executePipelined(RedisCallback<?> action) {
return executePipelined(action, valueSerializer);
}
/**
* Callback interface for Redis 'low level' code. To be used with {@link RedisTemplate} execution methods, often as
* anonymous classes within a method implementation. Usually, used for chaining several operations together (
* {@code get/set/trim etc...}.
*
* @author Costin Leau
*/
public interface RedisCallback<T> {

/**
* Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or
* closing the connection or handling exceptions.
*
* @param connection active Redis connection
* @return a result object or {@code null} if none
* @throws DataAccessException
*/
@Nullable
T doInRedis(RedisConnection connection) throws DataAccessException;
}

在IDEA里面的类redisConnection中点击编辑器菜单的Naviagate的type hierarchy然后就可以看到类的结构:


二十八、redis的批量查询_redis_02 image.png

下面给出一个实例:

List<String> redisKeys = new ArrayList<>();
redisKeys.add("name");
redisKeys.add("age");
redisKeys.add("height");
List<Object> result = redisTemplate.executePipelined(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection src = (StringRedisConnection)connection;
for(String k:redisKeys){
src.get(k);
}
return null;
}
});