java实现zookeeper分布式锁

Curator

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
zookeeper:
  address: 192.168.139.101:2181
  timeout: 4000
package com.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CuratorConfig {
    @Value("${zookeeper.address}")
    private String zkUrl;

    @Bean(initMethod = "start",destroyMethod = "close")
    public CuratorFramework curatorFrameworkClient() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkUrl, retryPolicy);
        return client;
    }
}

@Autowired
private CuratorFramework client;

@GetMapping("/curator")
public String curator() {
    String lockPath = "/lock";
    InterProcessMutex lock = new InterProcessMutex(client, lockPath);
    try {
        if (lock.acquire(10, TimeUnit.SECONDS)) {
            log.info("获取到锁");
            Thread.sleep(10000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        log.info("释放锁");
        try {
        	// 如果不释放,不会唤起其他线程,则其他线程会过期自动唤醒,不会执行业务代码
            lock.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "执行完毕";
}

自定义实现zk锁

package com.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Slf4j
public class ZkLock implements AutoCloseable, Watcher {

    public ZooKeeper zooKeeper;

    public String zNode;

    public ZkLock(String addr, Integer expireTime) throws IOException {
        this.zooKeeper = new ZooKeeper(addr, expireTime, this);
    }

    public ZkLock() throws IOException {
        this.zooKeeper = new ZooKeeper("192.168.139.101:2181", 10000, this);
    }

    public boolean getLock(String businessCode) {
        try {
            Stat stat = zooKeeper.exists("/" + businessCode, false);
            if (stat == null) {
                zooKeeper.create("/" + businessCode, businessCode.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
//          有序瞬时节点
            zNode = zooKeeper.create("/" + businessCode + "/" + businessCode + "_", businessCode.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

            List<String> children = zooKeeper.getChildren("/" + businessCode, false);
            Collections.sort(children);
            String first = children.get(0);
            if (zNode.endsWith(first)) {
                return true;
            }
//          不是一个节点,则监听前一个节点
            String last = first;
            for (String node : children) {
                if (zNode.endsWith(node)) {
                    zooKeeper.exists("/" + businessCode + "/" + last, true);
                } else {
                    last = node;
                }
            }

            synchronized (this) {
                wait();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    public void close() throws Exception {
        zooKeeper.delete(zNode, -1);
        zooKeeper.close();
        log.info("我已经释放了锁");
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
            synchronized (this) {
                notify();
            }
        }
    }
}

@GetMapping("/lock")
public String lock() throws IOException {
    log.info("进入方法");
    try(ZkLock zkLock = new ZkLock()) {
        if (zkLock.getLock("order")) {
            log.info("我获取到锁");
            Thread.sleep(10000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    log.info("执行完毕");
    return "";
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值