詳解如何在springcloud分布式系統(tǒng)中實(shí)現(xiàn)分布式鎖
最近在看分布式鎖的資料,看了 Josial L的《Redis in Action》的分布式鎖的章節(jié)。實(shí)現(xiàn)思路是利用springcloud結(jié)合redis實(shí)現(xiàn)分布式鎖。
注意:這篇文章有問(wèn)題,請(qǐng)看這一篇http://www.dbjr.com.cn/article/228819.htm
一、簡(jiǎn)介
一般來(lái)說(shuō),對(duì)數(shù)據(jù)進(jìn)行加鎖時(shí),程序先通過(guò)acquire獲取鎖來(lái)對(duì)數(shù)據(jù)進(jìn)行排他訪問(wèn),然后對(duì)數(shù)據(jù)進(jìn)行一些列的操作,最后需要釋放鎖。Redis 本身用 watch命令進(jìn)行了加鎖,這個(gè)鎖是樂(lè)觀鎖。使用 watch命令對(duì)于頻繁訪問(wèn)的鍵會(huì)引起性能的問(wèn)題。
二、redis命令介紹
SETNX命令(SET if Not eXists)
當(dāng)且僅當(dāng) key 不存在,將 key 的值設(shè)為 value ,并返回1;若給定的 key 已經(jīng)存在,則 SETNX 不做任何動(dòng)作,并返回0。
SETEX命令
設(shè)置超時(shí)時(shí)間
GET命令
返回 key 所關(guān)聯(lián)的字符串值,如果 key 不存在那么返回特殊值 nil 。
DEL命令
刪除給定的一個(gè)或多個(gè) key ,不存在的 key 會(huì)被忽略。
三、實(shí)現(xiàn)思路
由于redis的setnx命令天生就適合用來(lái)實(shí)現(xiàn)鎖的功能,這個(gè)命令只有在鍵不存在的情況下為鍵設(shè)置值。獲取鎖之后,其他程序再設(shè)置值就會(huì)失敗,即獲取不到鎖。獲取鎖失敗。只需不斷的嘗試獲取鎖,直到成功獲取鎖,或者到設(shè)置的超時(shí)時(shí)間為止。
另外為了防治死鎖,即某個(gè)程序獲取鎖之后,程序出錯(cuò),沒(méi)有釋放,其他程序無(wú)法獲取鎖,從而導(dǎo)致整個(gè)分布式系統(tǒng)無(wú)法獲取鎖而導(dǎo)致一系列問(wèn)題,甚至導(dǎo)致系統(tǒng)無(wú)法正常運(yùn)行。這時(shí)需要給鎖設(shè)置一個(gè)超時(shí)時(shí)間,即setex命令,鎖超時(shí)后,從而其它程序就可以獲取鎖了。
四、編碼實(shí)現(xiàn)
本文采用springboot結(jié)合redis 取實(shí)現(xiàn)的,所以你需要裝一個(gè)redis。
首先引入創(chuàng)建springboot工程,引入redis 。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 開(kāi)啟web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.創(chuàng)建一個(gè)鎖類(lèi)
/** * 全局鎖,包括鎖的名稱(chēng) * Created by fangzhipeng on 2017/4/1. */ public class Lock { private String name; private String value; public Lock(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
3.創(chuàng)建分布式鎖的具體方法,思路已經(jīng)說(shuō)清楚了,代碼注釋也寫(xiě)好了,就不講解了。
import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * Created by fangzhipeng on 2017/4/1. */ @Component public class DistributedLockHandler { private static final Logger logger = LoggerFactory.getLogger(DistributedLockHandler.class); private final static long LOCK_EXPIRE = 30 * 1000L;//單個(gè)業(yè)務(wù)持有鎖的時(shí)間30s,防止死鎖 private final static long LOCK_TRY_INTERVAL = 30L;//默認(rèn)30ms嘗試一次 private final static long LOCK_TRY_TIMEOUT = 20 * 1000L;//默認(rèn)嘗試20s @Autowired private StringRedisTemplate template; /** * 嘗試獲取全局鎖 * * @param lock 鎖的名稱(chēng) * @return true 獲取成功,false獲取失敗 */ public boolean tryLock(Lock lock) { return getLock(lock, LOCK_TRY_TIMEOUT, LOCK_TRY_INTERVAL, LOCK_EXPIRE); } /** * 嘗試獲取全局鎖 * * @param lock 鎖的名稱(chēng) * @param timeout 獲取超時(shí)時(shí)間 單位ms * @return true 獲取成功,false獲取失敗 */ public boolean tryLock(Lock lock, long timeout) { return getLock(lock, timeout, LOCK_TRY_INTERVAL, LOCK_EXPIRE); } /** * 嘗試獲取全局鎖 * * @param lock 鎖的名稱(chēng) * @param timeout 獲取鎖的超時(shí)時(shí)間 * @param tryInterval 多少毫秒嘗試獲取一次 * @return true 獲取成功,false獲取失敗 */ public boolean tryLock(Lock lock, long timeout, long tryInterval) { return getLock(lock, timeout, tryInterval, LOCK_EXPIRE); } /** * 嘗試獲取全局鎖 * * @param lock 鎖的名稱(chēng) * @param timeout 獲取鎖的超時(shí)時(shí)間 * @param tryInterval 多少毫秒嘗試獲取一次 * @param lockExpireTime 鎖的過(guò)期 * @return true 獲取成功,false獲取失敗 */ public boolean tryLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) { return getLock(lock, timeout, tryInterval, lockExpireTime); } /** * 操作redis獲取全局鎖 * * @param lock 鎖的名稱(chēng) * @param timeout 獲取的超時(shí)時(shí)間 * @param tryInterval 多少ms嘗試一次 * @param lockExpireTime 獲取成功后鎖的過(guò)期時(shí)間 * @return true 獲取成功,false獲取失敗 */ public boolean getLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) { try { if (StringUtils.isEmpty(lock.getName()) || StringUtils.isEmpty(lock.getValue())) { return false; } long startTime = System.currentTimeMillis(); do{ if (!template.hasKey(lock.getName())) { ValueOperations<String, String> ops = template.opsForValue(); ops.set(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS); return true; } else {//存在鎖 logger.debug("lock is exist!??!"); } if (System.currentTimeMillis() - startTime > timeout) {//嘗試超過(guò)了設(shè)定值之后直接跳出循環(huán) return false; } Thread.sleep(tryInterval); } while (template.hasKey(lock.getName())) ; } catch (InterruptedException e) { logger.error(e.getMessage()); return false; } return false; } /** * 釋放鎖 */ public void releaseLock(Lock lock) { if (!StringUtils.isEmpty(lock.getName())) { template.delete(lock.getName()); } } }
4.用法:
@Autowired DistributedLockHandler distributedLockHandler; Lock lock=new Lock("lockk","sssssssss); if(distributedLockHandler.tryLock(lock){ doSomething(); distributedLockHandler.releaseLock(); }
五、注意點(diǎn)
在使用全局鎖時(shí)為了防止死鎖采用 setex命令,這種命令需要根據(jù)具體的業(yè)務(wù)具體設(shè)置鎖的超時(shí)時(shí)間。另外一個(gè)就是鎖的粒度性。比如在redis實(shí)戰(zhàn)中有個(gè)案列,為了實(shí)現(xiàn)買(mǎi)賣(mài)市場(chǎng)交易的功能,把整個(gè)交易市場(chǎng)都鎖住了,導(dǎo)致了性能不足的情況,改進(jìn)方案只對(duì)買(mǎi)賣(mài)的商品進(jìn)行加鎖而不是整個(gè)市場(chǎng)。
六、參考資料
Josiah.L 《reids in action》
到此這篇關(guān)于詳解如何在springcloud分布式系統(tǒng)中實(shí)現(xiàn)分布式鎖的文章就介紹到這了,更多相關(guān)springcloud 分布式鎖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java保證對(duì)象在內(nèi)存中唯一性的實(shí)現(xiàn)方法
這篇文章主要介紹了java如何保證對(duì)象在內(nèi)存中的唯一性,如果創(chuàng)建多個(gè)對(duì)象的話,可能會(huì)引發(fā)出各種各樣的問(wèn)題,這時(shí),就需要我們保證這個(gè)對(duì)象在內(nèi)存中的唯一性,需要的朋友可以參考下2019-06-06永久解決 Intellij idea 報(bào)錯(cuò):Error :java 不支持發(fā)行版本5的問(wèn)題
這篇文章主要介紹了永久解決 Intellij idea 報(bào)錯(cuò):Error :java 不支持發(fā)行版本5的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02Java結(jié)構(gòu)型設(shè)計(jì)模式之享元模式示例詳解
享元模式(FlyWeight?Pattern),也叫蠅量模式,運(yùn)用共享技術(shù),有效的支持大量細(xì)粒度的對(duì)象,享元模式就是池技術(shù)的重要實(shí)現(xiàn)方式。本文將通過(guò)示例詳細(xì)講解享元模式,感興趣的可以了解一下2022-09-09解決spring cloud gateway 獲取body內(nèi)容并修改的問(wèn)題
這篇文章主要介紹了解決spring cloud gateway 獲取body內(nèi)容并修改的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12springboot啟動(dòng)時(shí)如何指定spring.profiles.active
這篇文章主要介紹了springboot啟動(dòng)時(shí)如何指定spring.profiles.active問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04java實(shí)現(xiàn)輕量型http代理服務(wù)器示例
這篇文章主要介紹了java實(shí)現(xiàn)輕量型http代理服務(wù)器示例,需要的朋友可以參考下2014-04-04