ZooKeeper分布式锁实现

1 Maven依赖

        这里我是通过Curator来对ZooKeeper进行连接的,pom依赖如下所示

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.13.0</version>
</dependency>

2 配置文件

zookeeper.connectAddress=127.0.0.1:2181
zookeeper.sessionTimeoutMs=10000

3 配置类

        分布式锁基于Curator的InterProcessMutex可重入锁来实现的,只需要注入相关的bean即可。具体的代码如下所示:

package com.hys.zookeeper.config;

import org.apache.curator.RetryPolicy;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @title: ZooKeeperConfig
 * @description: ZooKeeper配置类
 * @author: Robert Hou
 * @date: 2019年09月04日 20:20
 **/
@Configuration
public class ZooKeeperConfig {

    @Autowired
    private Environment environment;
    /**
     * 分布式锁节点
     */
    private static final String DISTRIBUTED_LOCK = "distributed-lock";

    @Bean
    public CuratorFramework curatorFramework() {
        String connectAddress = environment.getProperty("zookeeper.connectAddress");
        int sessionTimeoutMs = environment.getProperty("zookeeper.sessionTimeoutMs", Integer.class);
        //重试策略,初试时间为1s,重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder().connectString(connectAddress).sessionTimeoutMs(sessionTimeoutMs).retryPolicy(retryPolicy).build();
        cf.start();
        return cf;
    }

    @Bean
    public InterProcessMutex interProcessMutex() {
        CuratorFramework cf = curatorFramework();
        return new InterProcessMutex(cf, "/" + DISTRIBUTED_LOCK);
    }
}

4 测试代码

        这里用一个开启1000个线程来实现累加的例子来进行测试。每个线程实现num++的操作,正常情况下,最后的结果应该是1000。如果不进行任何的线程安全控制,结果应该是一个小于1000的值,且每次执行的结果都不一样。

package com.hys.zookeeper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ZookeeperApplicationTests {

    private static final Log logger = LogFactory.getLog(ZookeeperApplicationTests.class);

    @Autowired
    private InterProcessMutex interProcessMutex;
    private static int num;

    @Test
    public void contextLoads() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 1000; i++) {
            executorService.submit(() -> {
                try {
                    interProcessMutex.acquire();
                    Thread currentThread = Thread.currentThread();
                    System.out.println("线程" + currentThread.getId() + "获取锁成功");
                    num++;
                    System.out.println("线程" + currentThread.getId() + "获取锁结束");
                } catch (Exception e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e);
                    }
                } finally {
                    try {
                        interProcessMutex.release();
                    } catch (Exception e) {
                        if (logger.isErrorEnabled()) {
                            logger.error(e);
                        }
                    }
                    countDownLatch.countDown();
                }
            });
        }
        executorService.shutdown();
        countDownLatch.await();
        System.out.println(num);
    }
}

5 运行结果

        部分的运行结果如下所示:

线程78获取锁成功
线程78获取锁结束
线程84获取锁成功
线程84获取锁结束
线程239获取锁成功
线程239获取锁结束
//...
线程357获取锁成功
线程357获取锁结束
线程353获取锁成功
线程353获取锁结束
线程359获取锁成功
线程359获取锁结束
1000

        可以看到结果是1000,并且不存在线程交叉执行的情况出现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值