1、分布式锁是什么?
分布式锁是控制分布式系统之间同步访问共享资源的一种方式。
2、为什么需要分布式锁?
在分布式系统中,常常需要协调他们的动作。如果不同的系统或是同一个系统的不同主机之间共享了一个或一组资源,那么访问这些资源的时候,往往需要互斥来防止彼此干扰来保证一致性,在这种情况下,便需要使用到分布式锁。
3、乐观锁和悲观锁含义
悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。传统的关系型数据库里边就用到了很多这种锁机制,比如行锁,表锁等,读锁,写锁等,都是在做操作之前先上锁。
乐观锁(Optimistic Lock), 顾名思义,就是很乐观,每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据,可以使用版本号等机制。乐观锁适用于多读的应用类型,这样可以提高吞吐量,像数据库如果提供类似于write_condition机制的其实都是提供的乐观锁。
两种锁各有优缺点,不可认为一种好于另一种,像乐观锁适用于写比较少的情况下,即冲突真的很少发生的时候,这样可以省去了锁的开销,加大了系统的整个吞吐量。但如果经常产生冲突,上层应用会不断的进行retry,这样反倒是降低了性能,所以这种情况下用悲观锁就比较合适。
4、具体实现
本文采用zookeeper第三方库curator实现分布式锁。
1、添加依赖
<!-- Curator对Zookeeper封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.9.1</version>
</dependency>
<!-- Curator对Zookeeper封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>2.9.1</version>
</dependency>
<!-- Curator对Zookeeper封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.9.1</version>
</dependency>
2、锁的实现
public class ZKLockUtil {
/**Zookeeper注册中心地址*/
private static final String ZOOKEEPER_SERVER;
/**获取锁-每次尝试间隔(单位:毫秒)*/
private static final int BASE_SLEEP_TIME = 1000;
/**获取锁-最大尝试次数*/
private static final int MAX_RETRIES = 5;
/**Curator锁对象*/
private InterProcessMutex lock;
/**Curator客户端*/
private CuratorFramework client;
/**分布式锁根节点*/
private static final String ZK_BASE_LOCK_PATH = "/Locks/";
/**
* 初始化Zookeeper注册中心地址
*/
static {
ZOOKEEPER_SERVER = "172.24.20.214";
}
/**
*
* @author
* @created
* @since
* @param businessType
* @param baseSleepTimeMs
* @param maxRetries
* @throws
*/
private void initService(BusinessType businessType, int baseSleepTimeMs, int maxRetries) throws Exception {
if(isBlank(ZKLockUtil.ZOOKEEPER_SERVER)){
throw new Exception();
}
if(businessType == null || isBlank(businessType.getCode())){
throw new Exception();
}
try {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
this.client = CuratorFrameworkFactory.newClient(ZKLockUtil.ZOOKEEPER_SERVER, retryPolicy);
this.client.start();
this.setLock(new InterProcessMutex(this.client, ZK_BASE_LOCK_PATH.concat(businessType.getCode())));
} catch (Exception e) {
throw new Exception();
}
}
/**
*
* @author
* @created
* @since
* @param businessType
* @throws BusinessException
*/
public ZKLockUtil(BusinessType businessType) throws Exception {
this.initService(businessType, ZKLockUtil.BASE_SLEEP_TIME, ZKLockUtil.MAX_RETRIES);
}
/**
*
* 描述:构造函数
* @author mao2080@sina.com
* @created 2017年4月20日 下午3:52:53
* @since
* @param businessType 业务类型
* @param baseSleepTimeMs 获取锁-每次尝试间隔(单位:毫秒)
* @param maxRetries 获取锁-最大尝试次数
* @throws BusinessException
*/
public ZKLockUtil(BusinessType businessType, int baseSleepTimeMs, int maxRetries) throws Exception {
this.initService(businessType, baseSleepTimeMs, maxRetries);
}
/**
*
* @author
* @created
* @since
*/
public void close(){
try {
this.getLock().release();
} catch (Exception e) {
e.printStackTrace();
}
try {
this.client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author
* @created
* @since
* @param obj
* @return
*/
public static boolean isBlank(Object obj){
if(obj == null || "".equals(obj.toString())){
return true;
}
return false;
}
public InterProcessMutex getLock() {
return lock;
}
public void setLock(InterProcessMutex lock) {
this.lock = lock;
}
/**
*
* 业务类型
*/
public enum BusinessType {
Demo("0001", "Demo"),
;
/**业务类型编码 */
private String code;
/**业务类型名称 */
private String name;
/**
*
* 描述:构建业务类型
* @author mao2080@sina.com
* @created 2017年4月10日 下午3:42:57
* @since
* @param code 业务类型编码
* @param name 业务类型名称
* @return
*/
private BusinessType(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
System.out.println(BusinessType.Demo.code);
}
}
}
3、使用场景
/**
*锁工具类
*/
public class ZKLockUtilTest {
/**
*
* 具体使用样例
*
* @author
* @created
* @since
* @param args
* @throws Exception
*/
public static void main1(String[] args) throws Exception {
ZKLockUtil lock = new ZKLockUtil(BusinessType.Demo);
try {
if (lock.getLock().acquire(40, TimeUnit.SECONDS)) {
System.out.println("get lock success...do work");
Thread.sleep(20000);
}
} catch (Exception e) {
System.out.println("get lock fail...," + e.getMessage());
e.printStackTrace();
} finally {
lock.close();
}
}
/**
*启动线程模拟并发访问
*
* @author
* @created
* @since
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(5);
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.submit(new MyLock("client" + i, latch));
}
exec.shutdown();
latch.await();
System.out.println("所有任务执行完毕");
}
static class MyLock implements Runnable {
private String name;
private CountDownLatch latch;
public MyLock(String name, CountDownLatch latch) {
this.name = name;
this.latch = latch;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void run() {
ZKLockUtil locks = null;
try {
locks = new ZKLockUtil(BusinessType.Demo);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
try {
if (locks.getLock().acquire(40, TimeUnit.SECONDS)) {
System.out.println("----------" + this.name+ "获得资源----------");
System.out.println("----------" + this.name+ "正在处理资源----------");
Thread.sleep(1 * 2000);
System.out.println("----------" + this.name+ "资源使用完毕----------");
latch.countDown();
}
} catch (Exception e) {
System.out.println("get lock fail...," + e.getMessage());
e.printStackTrace();
} finally {
locks.close();
}
}
}
}
4、运行结果
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
----------client1获得资源----------
----------client1正在处理资源----------
----------client1资源使用完毕----------
----------client4获得资源----------
----------client4正在处理资源----------
----------client4资源使用完毕----------
----------client2获得资源----------
----------client2正在处理资源----------
----------client2资源使用完毕----------
----------client0获得资源----------
----------client0正在处理资源----------
----------client0资源使用完毕----------
----------client3获得资源----------
----------client3正在处理资源----------
----------client3资源使用完毕----------
所有任务执行完毕