这个比较好理解,分布式数字,类似AtomicInteger系列,Curator有2个实现:
第一个:
package curator.counters; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.shared.SharedCount; import org.apache.curator.framework.recipes.shared.SharedCountListener; import org.apache.curator.framework.recipes.shared.SharedCountReader; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; public class SharedCounterDemo { public static void main(String[] args) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(5000).connectionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("test").build(); client.start(); SharedCount count = new SharedCount(client,"/cut",0); count.start(); count.addListener(new SharedCountListener(){ @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { System.err.println("sharedCount.getCount : "+sharedCount.getCount()); System.err.println(newCount); }}); Thread.currentThread().sleep(5000); count.setCount(5); System.in.read(); } }
第二个:
package curator.counters; import org.apache.curator.RetryPolicy; 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.DistributedAtomicInteger; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.retry.RetryNTimes; public class DistributedAtomicIntegerDemo { public static void main(String[] args) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(5000).connectionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("test").build(); client.start(); DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client,"/autlog",new RetryNTimes(32,1000)); AtomicValue<Integer> rc = atomicInteger.add(8); System.out.println("success:" + rc.succeeded() + ";before:" + rc.preValue() + ";after:" + rc.postValue()); System.in.read(); } }