十四、curator recipes之DistributedAtomicLong
简介
和Java的AtomicLong没有太大的不同DistributedAtomicLong旨在分布式场景中维护一个Long类型的数据,你可以像普通单机环境一样来使用它。
官方文档:http://curator.apache.org/curator-recipes/distributed-atomic-long.html
代码示例
import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.atomic.AtomicValue; import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong; import org.apache.curator.retry.ExponentialBackoffRetry; public class DistributedAtomicLongDemo { private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 2)); private static String path = "/atomic/long/0001"; private static DistributedAtomicLong atomicLong = new DistributedAtomicLong(client, path, new ExponentialBackoffRetry(1000, 1)); static { client.start(); } public static void main(String[] args) throws Exception { System.out.println(atomicLong.get().postValue()); atomicLong.increment(); System.out.println(atomicLong.get().postValue()); atomicLong.decrement(); System.out.println(atomicLong.get().postValue()); AtomicValue<Long> newAtomicLong = atomicLong.compareAndSet(0L, 10L); System.out.println(newAtomicLong.succeeded()); System.out.println(newAtomicLong.preValue()); System.out.println(newAtomicLong.postValue()); System.out.println(atomicLong.get().postValue()); System.out.println(atomicLong.subtract(5L).postValue()); Thread.sleep(50000); client.close(); } }