java Curator实现分布式锁

Curator实现分布式锁主要依赖于zookeeper

// Curator实现分布式锁
			CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
														.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
// 必须先启动 否则无效过
			client.start();
			final InterProcessMutex lock = new InterProcessMutex(client, "/zk-xxx/childs");
			
			for(int i=0;i<10;i++){
				new Thread(){
					@Override
					public void run() {
						try {
							lock.acquire();
							System.out.println(code.getCode());
							lock.release();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();
			}


class GenerateCode{
	public String getCode(){
		SimpleDateFormat fomat = new SimpleDateFormat("HH:mm:ss|SSS");
		System.out.println("你的线程号:"+Thread.currentThread().getName());
		return fomat.format(new Date());
	}
}


<dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>2.7.0</version>
    </dependency>


猜你喜欢

转载自forlan.iteye.com/blog/2392200