掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網(wǎng)交流
分布式鎖是一種用于保證分布式系統(tǒng)中多個進程或線程同步訪問共享資源的技術。同時它又是面試中的常見問題,所以我們本文就重點來看分布式鎖的具體實現(xiàn)(含實現(xiàn)代碼)。

在分布式系統(tǒng)中,由于各個節(jié)點之間的網(wǎng)絡通信延遲、故障等原因,可能會導致數(shù)據(jù)不一致的問題。分布式鎖通過協(xié)調多個節(jié)點的行為,保證在任何時刻只有一個節(jié)點可以訪問共享資源,以避免數(shù)據(jù)的不一致性和沖突。
分布式鎖通常需要滿足以下幾個要求:
在 Java 中,實現(xiàn)分布式鎖的方案有多種,包括:
數(shù)據(jù)庫的樂觀鎖或悲觀鎖都可以實現(xiàn)分布式鎖,下面分別來看。
在數(shù)據(jù)庫中使用 for update 關鍵字可以實現(xiàn)悲觀鎖,我們在 Mapper 中添加 for update 即可對數(shù)據(jù)加鎖,實現(xiàn)代碼如下:
在 Service 中調用 Mapper 方法,即可獲取到加鎖的數(shù)據(jù):
@Transactional
public void updateWithPessimisticLock(int id, String name) {
User user = userMapper.selectByIdForUpdate(id);
if (user != null) {
user.setName(name);
userMapper.update(user);
} else {
throw new RuntimeException("數(shù)據(jù)不存在");
}
}在 MyBatis 中,可以通過給表添加一個版本號字段來實現(xiàn)樂觀鎖。在 Mapper 中,使用標簽定義更新語句,同時使用 set 標簽設置版本號的增量。
UPDATE user SET
name = #{name},
version = version + 1
WHERE id = #{id} AND version = #{version}
在 Service 中調用 Mapper 方法,需要傳入更新數(shù)據(jù)的版本號。如果更新失敗,說明數(shù)據(jù)已經(jīng)被其他事務修改,具體實現(xiàn)代碼如下:
@Transactional
public void updateWithOptimisticLock(int id, String name, int version) {
User user = userMapper.selectById(id);
if (user != null) {
user.setName(name);
user.setVersion(version);
int rows = userMapper.updateWithOptimisticLock(user);
if (rows == 0) {
throw new RuntimeException("數(shù)據(jù)已被其他事務修改");
}
} else {
throw new RuntimeException("數(shù)據(jù)不存在");
}
}在 Spring Boot 中,可以使用 Curator 框架來實現(xiàn) ZooKeeper 分布式鎖,具體實現(xiàn)分為以下 3 步:
org.apache.curator
curator-framework
latest
org.apache.curator
curator-recipes
latest
org.apache.zookeeper
zookeeper
latest
在 application.yml 中添加 ZooKeeper 連接配置:
spring:
zookeeper:
connect-string: localhost:2181
namespace: demo@Component
public class DistributedLock {
@Autowired
private CuratorFramework curatorFramework;
/**
* 獲取分布式鎖
*
* @param lockPath 鎖路徑
* @param waitTime 等待時間
* @param leaseTime 鎖持有時間
* @param timeUnit 時間單位
* @return 鎖對象
* @throws Exception 獲取鎖異常
*/
public InterProcessMutex acquire(String lockPath, long waitTime, long leaseTime, TimeUnit timeUnit) throws Exception {
InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);
if (!lock.acquire(waitTime, timeUnit)) {
throw new RuntimeException("獲取分布式鎖失敗");
}
if (leaseTime > 0) {
lock.acquire(leaseTime, timeUnit);
}
return lock;
}
/**
* 釋放分布式鎖
*
* @param lock 鎖對象
* @throws Exception 釋放鎖異常
*/
public void release(InterProcessMutex lock) throws Exception {
if (lock != null) {
lock.release();
}
}
}我們可以使用 Redis 客戶端 Redisson 實現(xiàn)分布式鎖,它的實現(xiàn)步驟如下:
在 pom.xml 中添加如下配置:
org.redisson
redisson-spring-boot-starter
3.20.0
在 Spring Boot 項目的配置文件 application.yml 中添加 Redisson 配置:
spring:
data:
redis:
host: localhost
port: 6379
database: 0
redisson:
codec: org.redisson.codec.JsonJacksonCodec
single-server-config:
address: "redis://${spring.data.redis.host}:${spring.redis.port}"
database: "${spring.data.redis.database}"
password: "${spring.data.redis.password}"import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedissonLockService {
@Resource
private Redisson redisson;
/**
* 加鎖
*
* @param key 分布式鎖的 key
* @param timeout 超時時間
* @param unit 時間單位
* @return
*/
public boolean tryLock(String key, long timeout, TimeUnit unit) {
RLock lock = redisson.getLock(key);
try {
return lock.tryLock(timeout, unit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
/**
* 釋放分布式鎖
*
* @param key 分布式鎖的 key
*/
public void unlock(String key) {
RLock lock = redisson.getLock(key);
lock.unlock();
}
}Redis 和 ZooKeeper 都可以用來實現(xiàn)分布式鎖,它們在實現(xiàn)分布式鎖的機制和原理上有所不同,具體區(qū)別如下:
總之,Redis 適合實現(xiàn)簡單的分布式鎖場景,而 ZooKeeper 適合實現(xiàn)復雜的分布式協(xié)調場景,也就是 ZooKeeper 適合強一致性的分布式系統(tǒng)。
“強一致性是指系統(tǒng)中的所有節(jié)點在任何時刻看到的數(shù)據(jù)都是一致的。ZooKeeper 中的數(shù)據(jù)是有序的樹形結構,每個節(jié)點都有唯一的路徑標識符,所有節(jié)點都共享同一份數(shù)據(jù),當任何一個節(jié)點對數(shù)據(jù)進行修改時,所有節(jié)點都會收到通知,更新數(shù)據(jù),并確保數(shù)據(jù)的一致性。在 ZooKeeper 中,強一致性體現(xiàn)在數(shù)據(jù)的讀寫操作上。ZooKeeper 使用 ZAB(ZooKeeper Atomic Broadcast)協(xié)議來保證數(shù)據(jù)的一致性,該協(xié)議確保了數(shù)據(jù)更新的順序,所有的數(shù)據(jù)更新都需要經(jīng)過集群中的大多數(shù)節(jié)點確認,保證了數(shù)據(jù)的一致性和可靠性?!?/p>
在 Java 中,使用數(shù)據(jù)庫、ZooKeeper 和 Redis 都可以實現(xiàn)分布式鎖。但數(shù)據(jù)庫 IO 操作比較慢,不適合高并發(fā)場景;Redis 執(zhí)行效率最高,但在主從切換時,可能會出現(xiàn)鎖丟失的情況;ZooKeeper 是一個高可用性的分布式協(xié)調服務,可以保證數(shù)據(jù)的強一致性,但是使用 ZooKeeper 需要部署額外的服務,增加了系統(tǒng)復雜度。所以沒有最好的解決方案,只有最合適自己的解決方案。

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網(wǎng)交流