美文网首页
Redis 分布式锁

Redis 分布式锁

作者: 杨健kimyeung | 来源:发表于2020-08-22 10:44 被阅读0次

一、背景

我们在开发很多业务场景会使用到锁,例如库存控制,抽奖等。一般我们会使用内存锁的方式来保证线性的执行。但现在大多站点都会使用分布式部署,

在传统单机部署的情况下,可以使用Java并发处理相关的API,例如: ReentrantLcok,synchronized**进行互斥控制。

但是在分布式系统后,由于分布式系统多线程、多进程并且分布在不同机器上,这将使原单机并发控制锁策略失效,为了解决这个问题就需要一种跨JVM的互斥机制来控制共享资源的访问,这就是分布式锁的由来

二、特点

1、互斥性:任意时刻,只能有一个客户端获取锁,不能同时有两个客户端获取到锁。

2、死锁:获取锁的客户端因为某些原因(如宕机时等)而未能释放锁,其它客户端再也无法获取到该锁。

3、容错:当部分节点(redis节点等)宕机时,客户端仍然能够获取锁和释放锁。

4、安全性:锁只能被持有该锁的客户端删除,不能由其它客户端删除。

三、实现方式

1、数据库乐观锁;

2、基于ZooKeeper的分布式锁;

3、基于Redis的分布式锁;

四、分布式锁(Redisson版)

接下来讲Redisson的分布式锁的实现,一般提及到Redis的分布式锁我们更多的使用的是Redisson的分布式锁,Redis的官方也是建议我们这样去做的。Redisson点我可以直接跳转到Redisson的官方文档。

[图片上传失败...(image-3dc76f-1598064238969)]

五、使用

1、引入Maven依赖

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="xml" cid="n20" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.11.6</version>
</dependency></pre>

2、配置redis信息

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n22" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">spring:
application:
name: redisson-lock-product
redis:
port: 6379
host: 127.0.0.1
password:
database: 0
timeout: 3000
redisson:

建议固定名字

config: classpath:redisson.yml</pre>

3、配置redisson.yml

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n24" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 单节点配置
singleServerConfig:

连接空闲超时,单位:毫秒

idleConnectionTimeout: 10000
pingTimeout: 1000

连接超时,单位:毫秒

connectTimeout: 10000

命令等待超时,单位:毫秒

timeout: 3000

命令失败重试次数,如果尝试达到 retryAttempts(命令失败重试次数) 仍然不能将命令发送至某个指定的节点时,将抛出错误。

如果尝试在此限制之内发送成功,则开始启用 timeout(命令等待超时) 计时。

retryAttempts: 3

命令重试发送时间间隔,单位:毫秒

retryInterval: 1500

重新连接时间间隔,单位:毫秒

reconnectionTimeout: 3000

执行失败最大次数

failedAttempts: 3

密码

password: null

单个连接最大订阅数量

subscriptionsPerConnection: 5

客户端名称

clientName: null

节点地址

address: redis://119.23.190.71:6379

address: redis://127.0.0.1:6379

发布和订阅连接的最小空闲连接数

subscriptionConnectionMinimumIdleSize: 1

发布和订阅连接池大小

subscriptionConnectionPoolSize: 50

最小空闲连接数

connectionMinimumIdleSize: 32

连接池大小

connectionPoolSize: 64

数据库编号

database: 1

DNS监测时间间隔,单位:毫秒

dnsMonitoringInterval: 5000
​</pre>

4、写一个RedissonConfig配置类 来配置你的redisson

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n26" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">package com.zw.smart.lock.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**

  • @author zhangwei
    */
    @Component
    public class RedissonLockUtil {
    @Resource
    private RedissonClient redissonClient;


/**

  • 加锁
  • @param lockKey
  • @return
    /
    public RLock lock(String lockKey) {
    RLock lock = redissonClient.getLock(lockKey);
    lock.lock();
    return lock;
    }

    /
    *
  • 释放锁
  • @param lockKey
    */
    public void unlock(String lockKey) {
    RLock lock = redissonClient.getLock(lockKey);
    lock.unlock();
    }

/**

  • 释放锁
  • @param lock
    /
    public void unlock(RLock lock) {
    lock.unlock();
    }

    /
    *
  • 带超时的锁
  • @param lockKey
  • @param timeout 超时时间 单位:秒
    */
    public RLock lock(String lockKey, int timeout) {
    RLock lock = redissonClient.getLock(lockKey);
    lock.lock(timeout, TimeUnit.SECONDS);
    return lock;
    }

/**

  • 带超时的锁
  • @param lockKey
  • @param unit 时间单位
  • @param timeout 超时时间
    */
    public RLock lock(String lockKey, TimeUnit unit , int timeout) {
    RLock lock = redissonClient.getLock(lockKey);
    lock.lock(timeout, unit);
    return lock;
    }

/**

  • 尝试获取锁
  • @param lockKey
  • @param waitTime 最多等待时间
  • @param leaseTime 上锁后自动释放锁时间
  • @return
    /
    public boolean tryLock(String lockKey, int waitTime, int leaseTime) {
    RLock lock = redissonClient.getLock(lockKey);
    try {
    return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    return false;
    }
    }
    /
    *
  • 尝试获取锁
  • @param lockKey
  • @param unit 时间单位
  • @param waitTime 最多等待时间
  • @param leaseTime 上锁后自动释放锁时间
  • @return
    */
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
    RLock lock = redissonClient.getLock(lockKey);
    try {
    return lock.tryLock(waitTime, leaseTime, unit);
    } catch (InterruptedException e) {
    return false;
    }
    }
    }</pre>

5、编写一个秒杀接口

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n28" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">​
@Resource
RedissonLockUtil redisLock;
@Override
public boolean decreProductStore(Long productId, Integer productQuantity) {
String key = "dec_store_lock_" + productId;

try {
//加锁 操作很类似Java的ReentrantLock机制
redisLock.lock(key,3,3);
ProductInfo productInfo = productMapper.selectByPrimaryKey(productId);
//如果库存为空
if (productInfo.getProductStock() == 0) {
return false;
}
//简单减库存操作 没有重新写其他接口了
productInfo.setProductStock(productInfo.getProductStock() - 1);
productMapper.updateByPrimaryKey(productInfo);
} catch (Exception e) {
log.info(e.getMessage())
} finally {
//解锁
redisLock.unlock();
}
return true;
}</pre>

1.6、写一个简单的测试请求

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n30" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">@GetMapping("order")
public String createOrderTest() {
if (!productInfoService.decrementProductStore(1L, 1)) {
return "库存不足";
}
OrderMaster orderMaster = new OrderMaster();
//未支付
orderMaster.setOrderStatus(0);
//未支付
orderMaster.setPayStatus(0);
orderMaster.setBuyerName(name);
orderMaster.setBuyerAddress("广东省广州市");
orderMaster.setBuyerPhone("186xxxxx");
orderMaster.setOrderAmount(BigDecimal.ZERO);
orderMaster.setCreateTime(DateUtils.getCurrentDate());
orderMaster.setOrderId(UUID.randomUUID().toString().replaceAll("-", ""));
orderMasterService.insert(orderMaster);
return "创建订单成功";
}</pre>

相关文章

网友评论

      本文标题:Redis 分布式锁

      本文链接:https://www.haomeiwen.com/subject/vwtvjktx.html