一、背景
我們在開發(fā)很多業(yè)務(wù)場景會使用到鎖,例如庫存控制,抽獎等。一般我們會使用內(nèi)存鎖的方式來保證線性的執(zhí)行。但現(xiàn)在大多站點(diǎn)都會使用分布式部署,
在傳統(tǒng)單機(jī)部署的情況下,可以使用Java并發(fā)處理相關(guān)的API,例如: ReentrantLcok,synchronized**進(jìn)行互斥控制。
但是在分布式系統(tǒng)后,由于分布式系統(tǒng)多線程、多進(jìn)程并且分布在不同機(jī)器上,這將使原單機(jī)并發(fā)控制鎖策略失效,為了解決這個(gè)問題就需要一種跨JVM的互斥機(jī)制來控制共享資源的訪問,這就是分布式鎖的由來
二、特點(diǎn)
1、互斥性:任意時(shí)刻,只能有一個(gè)客戶端獲取鎖,不能同時(shí)有兩個(gè)客戶端獲取到鎖。
2、死鎖:獲取鎖的客戶端因?yàn)槟承┰颍ㄈ珏礄C(jī)時(shí)等)而未能釋放鎖,其它客戶端再也無法獲取到該鎖。
3、容錯:當(dāng)部分節(jié)點(diǎn)(redis節(jié)點(diǎn)等)宕機(jī)時(shí),客戶端仍然能夠獲取鎖和釋放鎖。
4、安全性:鎖只能被持有該鎖的客戶端刪除,不能由其它客戶端刪除。
三、實(shí)現(xiàn)方式
1、數(shù)據(jù)庫樂觀鎖;
2、基于ZooKeeper的分布式鎖;
3、基于Redis的分布式鎖;
四、分布式鎖(Redisson版)
接下來講Redisson的分布式鎖的實(shí)現(xiàn),一般提及到Redis的分布式鎖我們更多的使用的是Redisson的分布式鎖,Redis的官方也是建議我們這樣去做的。Redisson點(diǎn)我可以直接跳轉(zhuǎn)到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;"># 單節(jié)點(diǎn)配置
singleServerConfig:
連接空閑超時(shí),單位:毫秒
idleConnectionTimeout: 10000
pingTimeout: 1000
連接超時(shí),單位:毫秒
connectTimeout: 10000
命令等待超時(shí),單位:毫秒
timeout: 3000
命令失敗重試次數(shù),如果嘗試達(dá)到 retryAttempts(命令失敗重試次數(shù)) 仍然不能將命令發(fā)送至某個(gè)指定的節(jié)點(diǎn)時(shí),將拋出錯誤。
如果嘗試在此限制之內(nèi)發(fā)送成功,則開始啟用 timeout(命令等待超時(shí)) 計(jì)時(shí)。
retryAttempts: 3
命令重試發(fā)送時(shí)間間隔,單位:毫秒
retryInterval: 1500
重新連接時(shí)間間隔,單位:毫秒
reconnectionTimeout: 3000
執(zhí)行失敗最大次數(shù)
failedAttempts: 3
密碼
password: null
單個(gè)連接最大訂閱數(shù)量
subscriptionsPerConnection: 5
客戶端名稱
clientName: null
節(jié)點(diǎn)地址
address: redis://119.23.190.71:6379
address: redis://127.0.0.1:6379
發(fā)布和訂閱連接的最小空閑連接數(shù)
subscriptionConnectionMinimumIdleSize: 1
發(fā)布和訂閱連接池大小
subscriptionConnectionPoolSize: 50
最小空閑連接數(shù)
connectionMinimumIdleSize: 32
連接池大小
connectionPoolSize: 64
數(shù)據(jù)庫編號
database: 1
DNS監(jiān)測時(shí)間間隔,單位:毫秒
dnsMonitoringInterval: 5000
?</pre>
4、寫一個(gè)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();
}
?
/* - 帶超時(shí)的鎖
- @param lockKey
- @param timeout 超時(shí)時(shí)間 單位:秒
*/
public RLock lock(String lockKey, int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, TimeUnit.SECONDS);
return lock;
}
/**
- 帶超時(shí)的鎖
- @param lockKey
- @param unit 時(shí)間單位
- @param timeout 超時(shí)時(shí)間
*/
public RLock lock(String lockKey, TimeUnit unit , int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, unit);
return lock;
}
/**
- 嘗試獲取鎖
- @param lockKey
- @param waitTime 最多等待時(shí)間
- @param leaseTime 上鎖后自動釋放鎖時(shí)間
- @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 時(shí)間單位
- @param waitTime 最多等待時(shí)間
- @param leaseTime 上鎖后自動釋放鎖時(shí)間
- @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、編寫一個(gè)秒殺接口
<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機(jī)制
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、寫一個(gè)簡單的測試請求
<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 "創(chuàng)建訂單成功";
}</pre>