zookeeper实现分布式锁

一、分布式锁产生的背景

      多机抢夺共享资源

二、分布式锁实现的三种方式

(1)基于数据库锁的是实现

(2)基于Redis的分布式锁实现(Reddisson)

(3)基于Zookeeper的分布式锁的实现

三、分布式锁实现满足的条件

(1)互斥性

(2)不会死锁

(3)具有容错性

(4)锁和解锁必须是同一个客户端

四、基于Zookeeper的分布式锁实现

(1)添加依赖
<dependency>
  <groupId>com.101tec</groupId>
  <artifactId>zkclient</artifactId>
  <version>0.4</version>
</dependency>
<dependency>
  <groupId>org.apache.curator</groupId>
  <artifactId>curator-recipes</artifactId>
  <version>2.11.1</version>
</dependency>
<dependency>
  <groupId>org.apache.curator</groupId>
  <artifactId>curator-client</artifactId>
  <version>2.11.1</version>
</dependency>

(2)添加配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 重连策略 -->
    <bean id="retryPolicy" class="org.apache.curator.retry.ExponentialBackoffRetry">
        <!-- 间隔时间基数 -->
        <constructor-arg index="0" value="1000"/>
        <!-- 重连策略 -->
        <constructor-arg index="1" value="3"/>
    </bean>

    <bean id="curatorFramework" class="org.apache.curator.framework.CuratorFrameworkFactory" factory-method="newClient"
          init-method="start">
        <constructor-arg index="0" value="自己的zookeeper地址"/>
        <constructor-arg index="1" ref="retryPolicy" />
    </bean>
</beans>

(3)编写工具类

@Slf4j
@Component
public class ZookeeperLockUtil {

    @Autowired
    private CuratorFramework curatorFramework;

    /**
     * 构建InterProcessMutex
     *
     * @param pathUrl 路径
     * @return 返回zookeeper路径对象
     */
    public InterProcessMutex builderInterProcessMutex(String pathUrl){
        return new InterProcessMutex(curatorFramework, pathUrl);
    }

    /**
     * 获取zookeeper锁
     * @param interProcessMutex 锁对象
     * @param timeout 超时时间
     * @return true成功 false失败
     */
    public boolean acquireLock(InterProcessMutex interProcessMutex, long timeout,TimeUnit unit){
        boolean flag = false;
        try {
            flag = interProcessMutex.acquire(timeout, unit);
        } catch (Exception e) {
            log.error("获取zookeeper锁异常,异常信息:",e);
        }
        if (flag){
            return true;
        }
        throw new BmServiceException(ErrorCodeEnum.BM_ZOOKEEPER_LOCK_ERROR);
    }

    /**
     * 释放zookeeper锁
     * @param interProcessMutex 锁对象
     */
    public void releaseLock(InterProcessMutex interProcessMutex){
        try {
            interProcessMutex.release();
        } catch (Exception e) {
            log.error("释放zookeeper锁异常,异常信息:",e);
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值