RedissonClient 做Map的累加处理的一些特性的补正的优化

RedissonClient 做Map的累加处理的一些特性的补正的优化

之前的文章RedissonClient 做Map的累加处理的一些特性的补正
在使用时,Map的Key 序列化出来后的值是"A1" ,而不是A1。看起来不太舒服,因此通过调研一番后,发现一个新的方案,所以继续水了一篇。

优化方案

使用CompositeCodec 这个编码器就可以了。这个编码可以可以分别指定MapKeyValue的编码器,比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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值