redis pipeline 使用

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);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值