版本依赖:
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.10.0</version>
</dependency>
示例代码如下:
package com.zk.lock;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
/**
* 全局锁简单示例
*/
public class MyLock implements Runnable
{
private final String clientName;
private final InterProcessMutex lock;
public MyLock(CuratorFramework client, String lockPath, String clientName)
{
this.clientName = clientName;
lock = new InterProcessMutex(client, lockPath);
}
public void work() throws Exception
{
//获取全局锁
lock.acquire();
try
{
System.out.println(clientName + "已经获取到锁");
for(int i=1;i<=3;i++)
{
System.out.println(clientName + " ---");
TimeUnit.MILLISECONDS.sleep(randomTime());
}
System.out.println(clientName + "释放锁");
}finally
{
//释放锁
lock.release();
}
}
private int randomTime()
{
Random r = new Random();
return r.nextInt(500) + r.nextInt(500);
}
public void run()
{
try
{
work();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
package com.zk.lock;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
* 模拟机器一(进程一)
*/
public class LockExample1
{
private static final String PATH = "/lock";
public static void main(String[] args) throws Exception
{
CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.1.246:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
TimeUnit.SECONDS.sleep(3);
String instance = "机器一";
for(int i=1;i<=3;i++)
{
new Thread(new MyLock(client, PATH, instance + i)).start();
}
TimeUnit.SECONDS.sleep(30);
client.close();
}
}
package com.zk.lock;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
* 模拟机器二(进程二)
*/
public class LockExample2
{
private static final String PATH = "/lock";
public static void main(String[] args) throws Exception
{
CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.1.246:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
TimeUnit.SECONDS.sleep(3);
String instance = "机器二";
for(int i=1;i<=3;i++)
{
new Thread(new MyLock(client, PATH, instance + i)).start();
}
TimeUnit.SECONDS.sleep(30);
client.close();
}
}
最后,同时运行上面两个example看效果