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

 

Kevin.Yang 2015-11-04 17:28:47  27769  收藏 2
展開
批量查詢的相關問題總結

再做測試之前首先向redis中批量插入一組數據

1-->1
2-->2
3-->3
4-->4
5-->5
6-->6
1
2
3
4
5
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));
        }
1
2
3
4
5
6
7
8
9
10
其打印結果是:

然而這並不是我們想要的,那怎樣才能知道打印的這個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());
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22


批量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();
————————————————
版權聲明:本文爲CSDN博主「Kevin.Yang」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/ouyang111222/article/details/49640899

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章