Apache Curator Lock 简单示例

版本依赖:

<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看效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值