springboot 整合redis 读取批量hash 取最优时间对比

1:循环读取:

        for (StockBean stockBean:stockBeans) {
            long t1=System.currentTimeMillis(); //获取开始时间
            String symbol=stockBean.getSymbol();
            Map map1=new HashMap<>();
            JSONObject object=JSONObject.parseObject(redisService.getCacheMap(symbol));
            map1.put(symbol,object.getString("price"));
            maps.add(map1);
            long t2=System.currentTimeMillis(); //获取结束时间
//            log.info("获取股票"+symbol+"需要时间:"+(t2-t1)+"ms");
        }
耗时:循环读取耗时:5393ms

2:批量读取:
 long t1 = System.currentTimeMillis(); //获取开始时间
        Collection collection=new ArrayList<>();
        for (StockBean stockBean:stockBeans){
            collection.add(stockBean.getSymbol());
        }

        List list = redisService.opsForHashGetWithPrices(collection);
        long t2=System.currentTimeMillis(); //获取结束时间
        log.info("批量读取耗时:"+(t2-t1)+"ms");
耗时:批量读取耗时:71ms

3:管道循环读取:
  Long time = System.currentTimeMillis();
        final List list1 = redisTemplate.executePipelined(new SessionCallback() {
            @Override
            public  Object execute(RedisOperations redisOperations) throws DataAccessException {
                for(StockBean stockBean:stockBeans){
                    Object dayil = redisTemplate.opsForHash().get("dayil", stockBean.getSymbol());
                }
                return null;
            }
        });
        System.out.println("管道循环读取耗时:" + (System.currentTimeMillis() - time)+"ms");
耗时:管道循环读取耗时:282ms

4:管道批量读取耗时
  Long time1= System.currentTimeMillis();

        redisTemplate.executePipelined(new SessionCallback() {
            @Override
            public  Object execute(RedisOperations redisOperations) throws DataAccessException {
                Collection collection=new ArrayList<>();
                for (StockBean stockBean:stockBeans){
                    collection.add(stockBean.getSymbol());
                }

                List list = redisService.opsForHashGetWithPrices(collection);
                return null;
            }
        });
        System.out.println("管道批量读取耗时:" + (System.currentTimeMillis() - time1)+"ms");
耗时:管道批量读取耗时:61ms


结果 :管道批量读取 61ms<批量读取 71ms<管道循环读取 282ms<循环读取 5393ms

循环读取:一个循环一个开关请求,等待处理结果,开关请求大大制约了redis 的读写性能,操作大批量数据应避免频繁开关请求。使用管道发送整个集合获取 
  

 

你可能感兴趣的:(redis,springboot,java)