當我們在單機情況下,遇到并發問題,可以使用juc包下的lock鎖,或者synchronized關鍵字來加鎖,但是這倆都是JVM級別的鎖,如果跨了JVM這兩個鎖就不能控制并發問題了,也就是說在分布式集群環境中,需要尋求其他方法來解決并發問題,前面也說到可以使用redis的setnx操作,如果不存在則set,如果存在則不set,也就是說每個服務實體都對同一個key進行操作,誰能set成功就認為獲取到了鎖,可以執行下面的操作,執行完之后釋放鎖,如下按照上述邏輯來簡單實作一個分布式鎖:
package com.nijunyang.redis.lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Created by nijunyang on 2020/3/17 23:53
*/
@RestController
public class LockController {
@Autowired
ValueOperations<String, Object> valueOperations;
@Autowired
RedisTemplate<String, Object> redisTemplate;
String lock = "lock";
String quantityKey = "quantity";
@GetMapping("/deduct-stock")
public String deductStock() {
try {
boolean getLock = valueOperations.setIfAbsent(lock, 1);
if (!getLock) {
return "沒有獲取到鎖";
}
//使用當做資料庫,只是模擬扣減庫存場景,因此不使用原子操作
Integer quantity = (Integer) valueOperations.get(quantityKey);
if (quantity > 0) {
--quantity;
valueOperations.set(quantityKey, quantity);
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
} else {
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
}
return "true";
} finally {
redisTemplate.delete(lock);
}
}
}
如果不出意外這個鎖是可以用的,但是如果拿到鎖之后,在執行業務的程序中,服務掛了,就會導致鎖沒有釋放,其他服務永遠無法拿到鎖,因此我們可以優化一下,加鎖的同時給鎖設定一個過期時間,這樣來保證,拿到鎖在執行業務的時候掛了,到了過期時間之后,其他服務一樣可以繼續獲取鎖,
package com.nijunyang.redis.lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
* Description:
* Created by nijunyang on 2020/3/17 23:53
*/
@RestController
public class LockController {
@Autowired
ValueOperations<String, Object> valueOperations;
@Autowired
RedisTemplate<String, Object> redisTemplate;
String lock = "lock";
String quantityKey = "quantity";
@GetMapping("/deduct-stock")
public String deductStock() {
try {
//設定值,并且設定超時時間
boolean getLock = valueOperations.setIfAbsent(lock, 1, 10, TimeUnit.SECONDS);
if (!getLock) {
return "沒有獲取到鎖";
}
//使用當做資料庫,只是模擬扣減庫存場景,因此不使用原子操作
Integer quantity = (Integer) valueOperations.get(quantityKey);
if (quantity > 0) {
--quantity;
valueOperations.set(quantityKey, quantity);
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
} else {
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
}
return "true";
} finally {
redisTemplate.delete(lock);
}
}
}
但是問題又來了,這個超時時間設定多大合適呢,如果網路延遲或者出現了sql的慢查詢等,導致業務還沒執行完,鎖就過期了,這個時候別的服務又拿到了鎖,現在并發問題問題又來了,,,A1服務拿到鎖,設定過期時間10s,但是業務邏輯需要15s才能執行完,10s過后鎖自動釋放,這時候A2服務拿到鎖執行業務,5s之后A1執行完業務洗掉鎖,但是這個時候A1釋放的是A2加的鎖,A2這個時候才執行5s,等到A2執行完去釋放的又是別的服務拿到的鎖,如此惡心回圈,,,,
這里整理了一些redis的相關學習資料,需要的朋友可以可以關注公眾號:Linux服務器 回復 redis獲取,


Linux服務器開發高級架構qun:720209036,

我們可以將鎖的value設定成一個客戶端的唯一值,比如生成一個UUID,洗掉的時候判斷一下這個值是否是自己生成,這樣就可以避免把其他服務加的鎖刪掉,
package com.nijunyang.redis.lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Description:
* Created by nijunyang on 2020/3/17 23:53
*/
@RestController
public class LockController {
@Autowired
ValueOperations<String, Object> valueOperations;
@Autowired
RedisTemplate<String, Object> redisTemplate;
String lock = "lock";
String quantityKey = "quantity";
@GetMapping("/deduct-stock")
public String deductStock() {
String uuid = UUID.randomUUID().toString();
try {
//設定值,并且設定超時時間
boolean getLock = valueOperations.setIfAbsent(lock, uuid, 10, TimeUnit.SECONDS);
// boolean getLock = valueOperations.setIfAbsent(lock, 1);
if (!getLock) {
return "沒有獲取到鎖";
}
//使用當做資料庫,只是模擬扣減庫存場景,因此不使用原子操作
Integer quantity = (Integer) valueOperations.get(quantityKey);
if (quantity > 0) {
--quantity;
valueOperations.set(quantityKey, quantity);
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
} else {
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
}
return "true";
} finally {
//洗掉之前判斷是否是自己加的鎖
if (uuid.equals(valueOperations.get(lock))) {
redisTemplate.delete(lock);
}
}
}
}
這樣只是保證自己的鎖不被別人刪掉,但是這個判斷再洗掉的操作也不是原子操作,同時超時的問題還是沒有解決,怎么辦呢,我們給鎖續命,可以在加鎖的同時再起一個定時任務,去檢查鎖是否釋放,如果沒有釋放就增加超時時間,然后再去定時檢查,直到鎖被洗掉了,比如鎖超時時間10s,那么定時任務在8s后去檢查,鎖是否被釋放,如果沒有釋放則重新設定超時時間,繼續監視鎖是否釋放,
如果我們自己按照這個邏輯去實作,有可能還會有很多bug,Redisson已經幫我們很好的實作了分布式鎖,配置好之后,使用就像使用java的lock一樣,原理就和上述差不多,
加依賴:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
寫配置:
@Bean
public Redisson redisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("xxx");
/**
* 哨兵
*/
//config.useSentinelServers().addSentinelAddress("");
/**
* 集群
*/
//config.useClusterServers().addNodeAddress("redis://111.229.53.45:6379");
return (Redisson) Redisson.create(config);
}
使用:
package com.nijunyang.redis.lock;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Description:
* Created by nijunyang on 2020/3/17 23:53
*/
@RestController
public class LockController {
@Autowired
ValueOperations<String, Object> valueOperations;
@Autowired
RedisTemplate<String, Object> redisTemplate;
@Autowired
Redisson redisson;
String lockKey = "lockKey";
String quantityKey = "quantity";
@GetMapping("/deduct-stock2")
public String deductStock2() {
RLock redissonLock = redisson.getLock(lockKey);
try {
redissonLock.lock();
//使用當做資料庫,只是模擬扣減庫存場景,因此不使用原子操作
Integer quantity = (Integer) valueOperations.get(quantityKey);
if (quantity > 0) {
--quantity;
valueOperations.set(quantityKey, quantity);
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
return "true";
} else {
System.out.println("扣減庫存成功,剩余庫存: " + quantity);
return "false";
}
} finally {
redissonLock.unlock();
}
}
}
和JUC包里面Lock鎖的使用一模一樣,有木有?
Redisson鎖原始碼邏輯簡要分析,直接在代碼中加的注釋說明,里面大量使用lua腳本來封裝redis操作的原子性,上面提到的判斷再洗掉的操作,也可以寫成lua腳本執行,保證原子性,同時lua腳本中如果出錯了,資料還會回滾,




雖然看起來已經很完善了,但是還有一點點問題如果哨兵模式,或者集群模式,鎖加載master上面,還未同步到slave的時候,master掛了,這個重新選舉,新的master上面是沒有加鎖的,不過這種幾率已經很小很小了,如果是在要求強一致性,那么就只有選擇zookeeper來實作,因為zookeeper是強一致性的,它是多數節點資料都同步好了才回傳,Master掛了,選舉也是在資料一致的節點中,因此重新選上來leader肯定是有鎖的,當然ZK的性能肯定就沒有redis的高了,怎么選擇還是看自己業務是否允許,
Redisson也提供了一個RedissonRedLock,傳入多個鎖物件,加鎖的時候,多個鎖都加上才認為加鎖成功,但是這樣需要連接多個redis,這樣肯定是有性能問題的,還有網路問題等等,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/237635.html
標籤:java
