一、分布式锁产生的背景
多机抢夺共享资源
二、分布式锁实现的三种方式
(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); } } }