Redis中PipeLine使用(二)---批量get與批量set

weixin_34320159發表於2018-12-17

批量查詢的相關問題總結
再做測試之前首先向redis中批量插入一組資料

1-->1
2-->2
3-->3
4-->4
5-->5
6-->6

現在批量get資料

for (Entry<String,String> entry :map.entrySet())     
        {
             pipe.get(entry.getKey().getBytes());
        }
        List<Object> list=pipe.syncAndReturnAll();

        for(Object o:list){
            byte[] tmp=(byte[])o;
            System.out.println("---->"+new String(tmp));
        }

其列印結果是:


4055666-43aadf3c2042aece.png
image.png

然而這並不是我們想要的,那怎樣才能知道列印的這個value對應的key呢?
這樣的應用場景很多,我們首先批量從redis get資料出來,然後將get的資料與記憶體中的資料進行執行在批量寫入資料庫!
這是需要引入一個HashMap

HashMap<String, String> map=new HashMap<String, String>();
        map.put("1","1");
        map.put("2","2");
        map.put("3","3");
        map.put("4","4");
        map.put("5","5");
        map.put("6","6");

        Pipeline pipe=redis.pipelined();

        HashMap<byte[], Response<byte[]>> newMap=new HashMap<byte[], Response<byte[]>>();

        for (Entry<String,String> entry :map.entrySet()) {
            newMap.put(entry.getKey().getBytes(), pipe.get(entry.getKey().getBytes()));
        }

        pipe.sync();

        for (Entry<byte[], Response<byte[]>> entry :newMap.entrySet()) {
            Response<byte[]> sResponse=(Response<byte[]>)entry.getValue();
            System.out.println(new String(entry.getKey())+"-----"+new String(sResponse.get()).toString());
        }
4055666-9ed919dbcdc662a4.png
image.png

批量get之後與記憶體的資料想加再批量set

HashMap<String, String> map=new HashMap<String, String>();
        map.put("1","1");
        map.put("2","2");
        map.put("3","3");
        map.put("4","4");
        map.put("5","5");
        map.put("6","6");

        Pipeline pipe=redis.pipelined();

        HashMap<byte[], Response<byte[]>> newMap=new HashMap<byte[], Response<byte[]>>();

        for (Entry<String,String> entry :map.entrySet()) {
            newMap.put(entry.getKey().getBytes(), pipe.get(entry.getKey().getBytes()));
        }

        pipe.sync();

        for (Entry<byte[], Response<byte[]>> entry :newMap.entrySet()) {
            Response<byte[]> sResponse=(Response<byte[]>)entry.getValue();
            long temp=Long.valueOf(Long.parseLong(map.get(new String(entry.getKey())))+Long.parseLong(new String(sResponse.get()).toString()));
            map.put(new String(entry.getKey()), Long.toString(temp));
        }

        for (Entry<String,String> entry :map.entrySet()) {
           pipe.set(entry.getKey().getBytes(), entry.getValue().getBytes());
        }
        pipe.sync();

相關文章