Zookeeper实现分布式锁的一种方式

zookeeper 分布式锁

  • zk服务端版本为 3.4.0
  • 使用 zk客户端为 curator

https://curator.apache.org/curator-framework/index.html

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.8.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.0</version>
</dependency>

package zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ZkLockUtil {

    private InterProcessMutex interProcessMutex;

    public ZkLockUtil(String zkServerAddress, String key) {

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkServerAddress)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(3000, 3, 30000))
                .build();
        client.start();
        String path = "/lock/Zk" + key;
        interProcessMutex = new InterProcessMutex(client, path);
    }

    public boolean tryLock(long timeout, TimeUnit unit) {
        try {
            return interProcessMutex.acquire(timeout, unit);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public boolean unlock() {
        try {
            interProcessMutex.release();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        return true;
    }

    public static void main(String[] args) {
        Runnable runnable = () -> {
            String name = Thread.currentThread().getName();

            ZkLockUtil zkLockUtil = new ZkLockUtil("127.0.0.1:2181", "101");
            boolean lock = zkLockUtil.tryLock(100, TimeUnit.SECONDS); // tryLock(2, TimeUnit.SECONDS);
            if (lock) {
                System.out.println(name + ":获取到锁");
                try {
                    Thread.sleep(10000);
                    System.out.println(name + ":业务完成");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    zkLockUtil.unlock();
                    System.out.println(name + ":释放锁\n");
                }
            } else {
                System.out.println(name + ":未获取到锁");
            }
        };

        new Thread(runnable, "线程1").start();
        new Thread(runnable, "线程2").start();
        new Thread(runnable, "线程3").start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值