pipline :可以将命令统一打包发送到redis服务端。
如果执行 n 次的话(比如 n 次 set 操作),网络耗时时间开销是非常大的。由于命令时间非常短,影响时间开销的主要是网络时间,所以我们可以把一组命令打包,然后一次发送过去。这样的话,时间开销就变为:
1次网络耗时+n次命令耗时。
public static void main(String[] args) {
Map<String, Integer> result = Maps.newHashMap();
Jedis jedis = null;
List<String> spuIds = Lists.newArrayList("123");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
String ip = ""; // redis server ip
int port = 6379;
int timeout = 2000;
jedisPoolConfig.setMaxTotal(1024);
jedisPoolConfig.setMaxIdle(100);
jedisPoolConfig.setMaxWaitMillis(100);
jedisPoolConfig.setTestOnReturn(true);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, ip, port, timeout);
HashMap<String, Response<String>> valueMap = Maps.newHashMap();
try {
// 批量获取redis
jedis = jedisPool.getResource();
Pipeline pipeline = jedis.pipelined();
for (String userId : userIds) {
valueMap.put(userId, pipeline.hget(hKey, userId));
}
pipeline.sync();
} catch (Exception e) {
……
} finally {
if (jedis != null) {
jedis.close(); // 注意一定要关闭连接
}
}
for (Map.Entry<String, Response<String>> entry : valueMap.entrySet()) {
Response<String> redisResponse = (Response<String>)entry.getValue();
String key = entry.getKey();
Integer value = redisResponse.get() == null ? 0 : Integer.parseInt(redisResponse.get());
result.put(key, value);
}
}