Java(SpringBoot)基于zookeeper的分布式锁实现

通过zookeeper实现分布式锁

1、创建zookeeper的client

首先通过CuratorFrameworkFactory创建一个连接zookeeper的连接CuratorFramework client

public class CuratorFactoryBean implements FactoryBean<CuratorFramework>, InitializingBean, DisposableBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(ContractFileInfoController.class);

    private String connectionString;
    private int sessionTimeoutMs;
    private int connectionTimeoutMs;
    private RetryPolicy retryPolicy;
    private CuratorFramework client;

    public CuratorFactoryBean(String connectionString) {
        this(connectionString, 500, 500);
    }

    public CuratorFactoryBean(String connectionString, int sessionTimeoutMs, int connectionTimeoutMs) {
        this.connectionString = connectionString;
        this.sessionTimeoutMs = sessionTimeoutMs;
        this.connectionTimeoutMs = connectionTimeoutMs;
    }

    @Override
    public void destroy() throws Exception {
        LOGGER.info("Closing curator framework...");
        this.client.close();
        LOGGER.info("Closed curator framework.");
    }

    @Override
    public CuratorFramework getObject() throws Exception {
        return this.client;
    }

    @Override
    public Class<?> getObjectType() {
         return this.client != null ? this.client.getClass() : CuratorFramework.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isEmpty(this.connectionString)) {
            throw new IllegalStateException("connectionString can not be empty.");
        } else {
            if (this.retryPolicy == null) {
                this.retryPolicy = new ExponentialBackoffRetry(1000, 2147483647, 180000);
            }

            this.client = CuratorFrameworkFactory.newClient(this.connectionString, this.sessionTimeoutMs, this.connectionTimeoutMs, this.retryPolicy);
            this.client.start();
            this.client.blockUntilConnected(30, TimeUnit.MILLISECONDS);
        }
    }
    public void setConnectionString(String connectionString) {
        this.connectionString = connectionString;
    }

    public void setSessionTimeoutMs(int sessionTimeoutMs) {
        this.sessionTimeoutMs = sessionTimeoutMs;
    }

    public void setConnectionTimeoutMs(int connectionTimeoutMs) {
        this.connectionTimeoutMs = connectionTimeoutMs;
    }

    public void setRetryPolicy(RetryPolicy retryPolicy) {
        this.retryPolicy = retryPolicy;
    }

    public void setClient(CuratorFramework client) {
        this.client = client;
    }
}

2、封装分布式锁

根据CuratorFramework创建InterProcessMutex(分布式可重入排它锁)对一行数据进行上锁

  public InterProcessMutex(CuratorFramework client, String path) {
        this(client, path, new StandardLockInternalsDriver());
    }

使用 acquire方法
1、acquire() :入参为空,调用该方法后,会一直堵塞,直到抢夺到锁资源,或者zookeeper连接中断后,上抛异常。
2、acquire(long time, TimeUnit unit):入参传入超时时间、单位,抢夺时,如果出现堵塞,会在超过该时间后,返回false。

  public void acquire() throws Exception {
        if (!this.internalLock(-1L, (TimeUnit)null)) {
            throw new IOException("Lost connection while trying to acquire lock: " + this.basePath);
        }
    }

    public boolean acquire(long time, TimeUnit unit) throws Exception {
        return this.internalLock(time, unit);
    }

释放锁 mutex.release();

  public void release() throws Exception {
        Thread currentThread = Thread.currentThread();
        InterProcessMutex.LockData lockData = (InterProcessMutex.LockData)this.threadData.get(currentThread);
        if (lockData == null) {
            throw new IllegalMonitorStateException("You do not own the lock: " + this.basePath);
        } else {
            int newLockCount = lockData.lockCount.decrementAndGet();
            if (newLockCount <= 0) {
                if (newLockCount < 0) {
                    throw new IllegalMonitorStateException("Lock count has gone negative for lock: " + this.basePath);
                } else {
                    try {
                        this.internals.releaseLock(lockData.lockPath);
                    } finally {
                        this.threadData.remove(currentThread);
                    }

                }
            }
        }
    }

封装后的DLock代码
1、调用InterProcessMutex processMutex = dLock.mutex(path);

2、手动释放锁processMutex.release();

3、需要手动删除路径dLock.del(path);

推荐 使用:
都是 函数式编程
在业务代码执行完毕后 会释放锁和删除path
1、这个有返回结果

public T mutex(String path, ZkLockCallback zkLockCallback, long time, TimeUnit timeUnit)

2、这个无返回结果

public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit)

public class DLock {
    private final Logger logger;
    private static final long TIMEOUT_D = 100L;
    private static final String ROOT_PATH_D = "/dLock";
    private String lockRootPath;
    private CuratorFramework client;

    public DLock(CuratorFramework client) {
        this("/dLock", client);
    }

    public DLock(String lockRootPath, CuratorFramework client) {
        this.logger = LoggerFactory.getLogger(DLock.class);
        this.lockRootPath = lockRootPath;
        this.client = client;
    }
    public InterProcessMutex mutex(String path) {
        if (!StringUtils.startsWith(path, "/")) {
            path = Constant.keyBuilder(new Object[]{"/", path});
        }

        return new InterProcessMutex(this.client, Constant.keyBuilder(new Object[]{this.lockRootPath, "", path}));
    }

    public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback) throws ZkLockException {
        return this.mutex(path, zkLockCallback, 100L, TimeUnit.MILLISECONDS);
    }

    public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {
        String finalPath = this.getLockPath(path);
        InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);

        try {
            if (!mutex.acquire(time, timeUnit)) {
                throw new ZkLockException("acquire zk lock return false");
            }
        } catch (Exception var13) {
            throw new ZkLockException("acquire zk lock failed.", var13);
        }

        T var8;
        try {
            var8 = zkLockCallback.doInLock();
        } finally {
            this.releaseLock(finalPath, mutex);
        }

        return var8;
    }

    private void releaseLock(String finalPath, InterProcessMutex mutex) {
        try {
            mutex.release();
            this.logger.info("delete zk node path:{}", finalPath);
            this.deleteInternal(finalPath);
        } catch (Exception var4) {
            this.logger.error("dlock", "release lock failed, path:{}", finalPath, var4);
//            LogUtil.error(this.logger, "dlock", "release lock failed, path:{}", new Object[]{finalPath, var4});
        }

    }

    public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {
        String finalPath = this.getLockPath(path);
        InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);

        try {
            if (!mutex.acquire(time, timeUnit)) {
                throw new ZkLockException("acquire zk lock return false");
            }
        } catch (Exception var13) {
            throw new ZkLockException("acquire zk lock failed.", var13);
        }

        try {
            zkLockCallback.response();
        } finally {
            this.releaseLock(finalPath, mutex);
        }

    }

    public String getLockPath(String customPath) {
        if (!StringUtils.startsWith(customPath, "/")) {
            customPath = Constant.keyBuilder(new Object[]{"/", customPath});
        }

        String finalPath = Constant.keyBuilder(new Object[]{this.lockRootPath, "", customPath});
        return finalPath;
    }

    private void deleteInternal(String finalPath) {
        try {
            ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(finalPath);
        } catch (Exception var3) {
            this.logger.info("delete zk node path:{} failed", finalPath);
        }

    }

    public void del(String customPath) {
        String lockPath = "";

        try {
            lockPath = this.getLockPath(customPath);
            ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(lockPath);
        } catch (Exception var4) {
            this.logger.info("delete zk node path:{} failed", lockPath);
        }

    }
}

@FunctionalInterface
public interface ZkLockCallback<T> {
T doInLock();
}

@FunctionalInterface
public interface ZkVoidCallBack {
void response();
}

public class ZkLockException extends Exception {
public ZkLockException() {
}

public ZkLockException(String message) {
    super(message);
}

public ZkLockException(String message, Throwable cause) {
    super(message, cause);
}

}

配置CuratorConfig

@Configuration
public class CuratorConfig {
@Value("${zk.connectionString}")
private String connectionString;

@Value("${zk.sessionTimeoutMs:500}")
private int sessionTimeoutMs;

@Value("${zk.connectionTimeoutMs:500}")
private int connectionTimeoutMs;

@Value("${zk.dLockRoot:/dLock}")
private String dLockRoot;

@Bean
public CuratorFactoryBean curatorFactoryBean() {
    return new CuratorFactoryBean(connectionString, sessionTimeoutMs, connectionTimeoutMs);
}

@Bean
@Autowired
public DLock dLock(CuratorFramework client) {
    return new DLock(dLockRoot, client);
}

}

测试代码

@RestController
@RequestMapping("/dLock")
public class LockController {

@Autowired
private DLock dLock;

@RequestMapping("/lock")
public Map testDLock(String no){
    final String path = Constant.keyBuilder("/test/no/", no);
    Long mutex=0l;
    try {
        System.out.println("在拿锁:"+path+System.currentTimeMillis());
         mutex = dLock.mutex(path, () -> {
            try {
                System.out.println("拿到锁了" + System.currentTimeMillis());
                Thread.sleep(10000);
                System.out.println("操作完成了" + System.currentTimeMillis());
            } finally {
                return System.currentTimeMillis();
            }
        }, 1000, TimeUnit.MILLISECONDS);
    } catch (ZkLockException e) {
        System.out.println("拿不到锁呀"+System.currentTimeMillis());
    }
    return Collections.singletonMap("ret",mutex);
}

@RequestMapping("/dlock")
public Map testDLock1(String no){
    final String path = Constant.keyBuilder("/test/no/", no);
    Long mutex=0l;
    try {
        System.out.println("在拿锁:"+path+System.currentTimeMillis());
        InterProcessMutex processMutex = dLock.mutex(path);
        processMutex.acquire();
        System.out.println("拿到锁了" + System.currentTimeMillis());
        Thread.sleep(10000);
        processMutex.release();
        System.out.println("操作完成了" + System.currentTimeMillis());
    } catch (ZkLockException e) {
        System.out.println("拿不到锁呀"+System.currentTimeMillis());
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }
    return Collections.singletonMap("ret",mutex);
}
@RequestMapping("/del")
public Map delDLock(String no){
    final String path = Constant.keyBuilder("/test/no/", no);
    dLock.del(path);
    return Collections.singletonMap("ret",1);
}

}

顺便在此给大家推荐一个Java方面的交流学习群:4112676,里面会分享一些高级面试题,还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系,主要针对Java开发人员提升自己,突破瓶颈,相信你来学习,会有提升和收获。在这个群里会有你需要的内容 朋友们请抓紧时间加入进来吧
![](https://upload-images.jianshu.io/upload_images/15593451-105071ff9a0abe56.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341

推荐阅读更多精彩内容