RedissonClient 做Map的累加处理的一些特性的补正的优化
之前的文章RedissonClient 做Map的累加处理的一些特性的补正
在使用时,Map的Key
序列化出来后的值是"A1"
,而不是A1
。看起来不太舒服,因此通过调研一番后,发现一个新的方案,所以继续水了一篇。
优化方案
使用CompositeCodec
这个编码器就可以了。这个编码可以可以分别指定Map
的Key
、Value
的编码器,比TypedJsonJacksonCodec
指定TypeReference
使用起来更方便。
测试代码
@Test
public void testIncrementWithRedisson2_5(){
String key = "testIncrementWithRedisson2_5";
String hashKey = "A1";
List<CompletableFuture> cfList = IntStream.range(1,201).mapToObj(r->{
return CompletableFuture.runAsync(()->
incrementWithRedisson4(key,hashKey)
,testExecutorService)
.exceptionally(ex->{
ex.printStackTrace();
return null;
});
}).collect(Collectors.toList());
// 等待所有线程结束
CompletableFuture.allOf(cfList.toArray(new CompletableFuture[cfList.size()])).whenComplete((k,e)->{
//所有线程都结束后,取出累加的值
//强制指定本Map的Codec 为compositeCodec
CompositeCodec compositeCodec = new CompositeCodec(StringCodec.INSTANCE,
LongCodec.INSTANCE
);
RMap<String,Long> accumulatorMap = redissonClient.getMap(key,compositeCodec);
Long value = accumulatorMap.get(hashKey);
System.out.println(String.format("累加的结果%d",value));
accumulatorMap.forEach((mapKey,mapValue)->{
System.out.println(mapKey+"-"+mapValue);
});
}).join();
}
private long incrementWithRedisson4(String key,String hashKey){
//强制指定本Map的Codec 为 CompositeCodec
CompositeCodec compositeCodec = new CompositeCodec(StringCodec.INSTANCE,
LongCodec.INSTANCE
);
RMap<String,Long> accumulatorMap = redissonClient.getMap(key, compositeCodec);
return accumulatorMap.addAndGet(hashKey,1L);
}
测试结果
redis的值:
控制台输出:
累加的结果200
A1-200