六、Curator使用:分布式计数器

时间:2019-11-18
本文章向大家介绍六、Curator使用:分布式计数器,主要包括六、Curator使用:分布式计数器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

分布式计数器介绍

和分布式锁类似,下面是实现分布式计数器的功能

代码

    //分布式计数器
    DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(cc,"/distributed_atomic_counter",new ExponentialBackoffRetry(1000,3));
    AtomicValue av = atomicInteger.add(10);
    System.out.println(av.succeeded());//true
    System.out.println(av.preValue());//0
    System.out.println(av.postValue());//10

每个DistributedAtomicXXX里面都有一个AtomicValue,这个是分布式的核心实现类。

    AtomicValue<byte[]>   trySet(MakeValue makeValue) throws Exception
    {
        MutableAtomicValue<byte[]>  result = new MutableAtomicValue<byte[]>(null, null, false);
        //尝试下乐观锁
        tryOptimistic(result, makeValue);
        if ( !result.succeeded() && (mutex != null) )
        {
            //失败的话再使用排他锁
            tryWithMutex(result, makeValue);
        }

        return result;
    }

原文地址:https://www.cnblogs.com/june777/p/11881340.html