zookeeper 分布式计数器
应用场景:分布式应用的计数场景
**********************************
相关类
public class DistributedAtomicInteger implements DistributedAtomicNumber<Integer> {
*****************************
构造方法
public DistributedAtomicInteger(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) {
public DistributedAtomicInteger(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) {
******************************
常用方法
public AtomicValue<Integer> get() throws Exception {
public AtomicValue<Integer> increment() throws Exception {
public AtomicValue<Integer> add(Integer delta) throws Exception {
public AtomicValue<Integer> decrement() throws Exception {
public AtomicValue<Integer> subtract(Integer delta) throws Exception {
**********************************
使用示例
******************
config 层
@Configuration
public class ZookeeperConfig {
@Value("${zookeeper.connecting-string}")
private String connectingString;
@Bean
public CuratorFramework initCuratorFramework(){
CuratorFramework curatorFramework= CuratorFrameworkFactory.builder()
.connectString(connectingString)
.sessionTimeoutMs(5000)
.retryPolicy(new ExponentialBackoffRetry(1000,3,3000))
.namespace("test")
.build();
curatorFramework.start();
return curatorFramework;
}
}
******************
controller 层
@RestController
public class HelloController {
@Autowired
private CuratorFramework curatorFramework;
private String countPath="/count";
@RequestMapping("/get")
public Integer get(){
DistributedAtomicInteger distributedAtomicInteger=new DistributedAtomicInteger(curatorFramework,countPath,new ExponentialBackoffRetry(1000,3,3000));
ExecutorService executorService=Executors.newFixedThreadPool(5);
for(int i=0;i<5;i++){
executorService.submit(()->{
try{
for(int j=0;j<100;j++){
distributedAtomicInteger.increment();
}
}catch (Exception e){
e.printStackTrace();
}
});
}
Integer result=null;
try{
result=distributedAtomicInteger.get().postValue();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}