redis使用管道pipeline实现批量新增和修改
解决方法:
1.核心方法
public static boolean pipelineHmset (int dbIndex,String key,List<Map<String, String>> list){
Jedis jedis = null;
try {
jedis = getJedis();//获取jedis实例
jedis.select(dbIndex);
Pipeline pip = jedis.pipelined();
for (Map<String, String> keysmap : list) {
//批量插入
pip.hmset(key, keysmap);
}
pip.sync();//同步
} catch (Exception e) {
e.printStackTrace();
}finally{
if (jedis != null) {
jedis.close();
}
}
return false;
}
2.使用方法
批量插入10条记录到redis的rd_table表中
public static void main(String[] args) throws Exception{
List<Map<String, String>> addList=new ArrayList<Map<String,String>>();
for(int i=1;i<10;i++){
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key"+i,"value"+i);
addList.add(hashMap);
}
if(addList.size()>0){
pipelineHmset(0, "rd_table", addList);
}
}