基于Redis分布式鎖的實(shí)現(xiàn)代碼
概述
目前幾乎很多大型網(wǎng)站及應(yīng)用都是分布式部署的,分布式場(chǎng)景中的數(shù)據(jù)一致性問(wèn)題一直是一個(gè)比較重要的話題。分布式的CAP理論告訴我們“任何一個(gè)分布式系統(tǒng)都無(wú)法同時(shí)滿足一致性(Consistency)、可用性(Availability)和分區(qū)容錯(cuò)性(Partition tolerance),最多只能同時(shí)滿足兩項(xiàng)。”所以,很多系統(tǒng)在設(shè)計(jì)之初就要對(duì)這三者做出取舍。在互聯(lián)網(wǎng)領(lǐng)域的絕大多數(shù)的場(chǎng)景中,都需要犧牲強(qiáng)一致性來(lái)?yè)Q取系統(tǒng)的高可用性,系統(tǒng)往往只需要保證“最終一致性”,只要這個(gè)最終時(shí)間是在用戶可以接受的范圍內(nèi)即可。
在很多場(chǎng)景中,我們?yōu)榱吮WC數(shù)據(jù)的最終一致性,需要很多的技術(shù)方案來(lái)支持,比如分布式事務(wù)、分布式鎖等。
選用Redis實(shí)現(xiàn)分布式鎖原因
Redis有很高的性能
Redis命令對(duì)此支持較好,實(shí)現(xiàn)起來(lái)比較方便
在此就不介紹Redis的安裝了。
使用命令介紹
SETNX
SETNX key val
當(dāng)且僅當(dāng)key不存在時(shí),set一個(gè)key為val的字符串,返回1;若key存在,則什么都不做,返回0。
expire
expire key timeout
為key設(shè)置一個(gè)超時(shí)時(shí)間,單位為second,超過(guò)這個(gè)時(shí)間鎖會(huì)自動(dòng)釋放,避免死鎖。
delete
delete key
刪除key
在使用Redis實(shí)現(xiàn)分布式鎖的時(shí)候,主要就會(huì)使用到這三個(gè)命令。
實(shí)現(xiàn)
使用的是jedis來(lái)連接Redis。
實(shí)現(xiàn)思想
獲取鎖的時(shí)候,使用setnx加鎖,并使用expire命令為鎖添加一個(gè)超時(shí)時(shí)間,超過(guò)該時(shí)間則自動(dòng)釋放鎖,鎖的value值為一個(gè)隨機(jī)生成的UUID,通過(guò)此在釋放鎖的時(shí)候進(jìn)行判斷。
獲取鎖的時(shí)候還設(shè)置一個(gè)獲取的超時(shí)時(shí)間,若超過(guò)這個(gè)時(shí)間則放棄獲取鎖。
釋放鎖的時(shí)候,通過(guò)UUID判斷是不是該鎖,若是該鎖,則執(zhí)行delete進(jìn)行鎖釋放。
分布式鎖的核心代碼如下:
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisException; import java.util.List; import java.util.UUID; /** * Created by liuyang on 2017/4/20. */ public class DistributedLock { private final JedisPool jedisPool; public DistributedLock(JedisPool jedisPool) { this.jedisPool = jedisPool; } /** * 加鎖 * @param locaName 鎖的key * @param acquireTimeout 獲取超時(shí)時(shí)間 * @param timeout 鎖的超時(shí)時(shí)間 * @return 鎖標(biāo)識(shí) */ public String lockWithTimeout(String locaName, long acquireTimeout, long timeout) { Jedis conn = null; String retIdentifier = null; try { // 獲取連接 conn = jedisPool.getResource(); // 隨機(jī)生成一個(gè)value String identifier = UUID.randomUUID().toString(); // 鎖名,即key值 String lockKey = "lock:" + locaName; // 超時(shí)時(shí)間,上鎖后超過(guò)此時(shí)間則自動(dòng)釋放鎖 int lockExpire = (int)(timeout / 1000); // 獲取鎖的超時(shí)時(shí)間,超過(guò)這個(gè)時(shí)間則放棄獲取鎖 long end = System.currentTimeMillis() + acquireTimeout; while (System.currentTimeMillis() < end) { if (conn.setnx(lockKey, identifier) == 1) { conn.expire(lockKey, lockExpire); // 返回value值,用于釋放鎖時(shí)間確認(rèn) retIdentifier = identifier; return retIdentifier; } // 返回-1代表key沒(méi)有設(shè)置超時(shí)時(shí)間,為key設(shè)置一個(gè)超時(shí)時(shí)間 if (conn.ttl(lockKey) == -1) { conn.expire(lockKey, lockExpire); } try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } catch (JedisException e) { e.printStackTrace(); } finally { if (conn != null) { conn.close(); } } return retIdentifier; } /** * 釋放鎖 * @param lockName 鎖的key * @param identifier 釋放鎖的標(biāo)識(shí) * @return */ public boolean releaseLock(String lockName, String identifier) { Jedis conn = null; String lockKey = "lock:" + lockName; boolean retFlag = false; try { conn = jedisPool.getResource(); while (true) { // 監(jiān)視lock,準(zhǔn)備開(kāi)始事務(wù) conn.watch(lockKey); // 通過(guò)前面返回的value值判斷是不是該鎖,若是該鎖,則刪除,釋放鎖 if (identifier.equals(conn.get(lockKey))) { Transaction transaction = conn.multi(); transaction.del(lockKey); List<Object> results = transaction.exec(); if (results == null) { continue; } retFlag = true; } conn.unwatch(); break; } } catch (JedisException e) { e.printStackTrace(); } finally { if (conn != null) { conn.close(); } } return retFlag; } }
測(cè)試
下面就用一個(gè)簡(jiǎn)單的例子測(cè)試剛才實(shí)現(xiàn)的分布式鎖。
例子中使用50個(gè)線程模擬秒殺一個(gè)商品,使用--運(yùn)算符來(lái)實(shí)現(xiàn)商品減少,從結(jié)果有序性就可以看出是否為加鎖狀態(tài)。
模擬秒殺服務(wù),在其中配置了jedis線程池,在初始化的時(shí)候傳給分布式鎖,供其使用。
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by liuyang on 2017/4/20. */ public class Service { private static JedisPool pool = null; static { JedisPoolConfig config = new JedisPoolConfig(); // 設(shè)置最大連接數(shù) config.setMaxTotal(200); // 設(shè)置最大空閑數(shù) config.setMaxIdle(8); // 設(shè)置最大等待時(shí)間 config.setMaxWaitMillis(1000 * 100); // 在borrow一個(gè)jedis實(shí)例時(shí),是否需要驗(yàn)證,若為true,則所有jedis實(shí)例均是可用的 config.setTestOnBorrow(true); pool = new JedisPool(config, "127.0.0.1", 6379, 3000); } DistributedLock lock = new DistributedLock(pool); int n = 500; public void seckill() { // 返回鎖的value值,供釋放鎖時(shí)候進(jìn)行判斷 String indentifier = lock.lockWithTimeout("resource", 5000, 1000); System.out.println(Thread.currentThread().getName() + "獲得了鎖"); System.out.println(--n); lock.releaseLock("resource", indentifier); } } // 模擬線程進(jìn)行秒殺服務(wù) public class ThreadA extends Thread { private Service service; public ThreadA(Service service) { this.service = service; } @Override public void run() { service.seckill(); } } public class Test { public static void main(String[] args) { Service service = new Service(); for (int i = 0; i < 50; i++) { ThreadA threadA = new ThreadA(service); threadA.start(); } } }
結(jié)果如下,結(jié)果為有序的。
若注釋掉使用鎖的部分
public void seckill() { // 返回鎖的value值,供釋放鎖時(shí)候進(jìn)行判斷 //String indentifier = lock.lockWithTimeout("resource", 5000, 1000); System.out.println(Thread.currentThread().getName() + "獲得了鎖"); System.out.println(--n); //lock.releaseLock("resource", indentifier); }
從結(jié)果可以看出,有一些是異步進(jìn)行的。
在分布式環(huán)境中,對(duì)資源進(jìn)行上鎖有時(shí)候是很重要的,比如搶購(gòu)某一資源,這時(shí)候使用分布式鎖就可以很好地控制資源。
當(dāng)然,在具體使用中,還需要考慮很多因素,比如超時(shí)時(shí)間的選取,獲取鎖時(shí)間的選取對(duì)并發(fā)量都有很大的影響,上述實(shí)現(xiàn)的分布式鎖也只是一種簡(jiǎn)單的實(shí)現(xiàn),主要是一種思想。
下一次我會(huì)使用zookeeper實(shí)現(xiàn)分布式鎖,使用zookeeper的可靠性是要大于使用redis實(shí)現(xiàn)的分布式鎖的,但是相比而言,redis的性能更好。
上面的代碼可以在我的GitHub中進(jìn)行查看。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- redis中使用java腳本實(shí)現(xiàn)分布式鎖
- 基于Redis實(shí)現(xiàn)分布式鎖以及任務(wù)隊(duì)列
- 詳解Java如何實(shí)現(xiàn)基于Redis的分布式鎖
- Redis實(shí)現(xiàn)分布式鎖的幾種方法總結(jié)
- Redis上實(shí)現(xiàn)分布式鎖以提高性能的方案研究
- 詳解使用Redis SETNX 命令實(shí)現(xiàn)分布式鎖
- Redis數(shù)據(jù)庫(kù)中實(shí)現(xiàn)分布式鎖的方法
- Redis構(gòu)建分布式鎖
- redisson實(shí)現(xiàn)分布式鎖原理
- 深入理解redis分布式鎖和消息隊(duì)列
相關(guān)文章
SpringBoot整合Redis實(shí)現(xiàn)序列化存儲(chǔ)Java對(duì)象的操作方法
這篇文章主要介紹了SpringBoot整合Redis實(shí)現(xiàn)序列化存儲(chǔ)Java對(duì)象,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03Redis的11種Web應(yīng)用場(chǎng)景簡(jiǎn)介
一些Redis原語(yǔ)命令比如LPUSH、LTRIM和 LREM等等能夠用來(lái)幫助開(kāi)發(fā)者完成需要的任務(wù)——這些任務(wù)在傳統(tǒng)的數(shù)據(jù)庫(kù)存儲(chǔ)中非常困難或緩慢。這是一篇非常有用并且實(shí)際的文章。那么要如何在你的框架中完成這些任務(wù)呢?2015-09-09Redis出現(xiàn)(error)NOAUTH?Authentication?required.報(bào)錯(cuò)的解決辦法(秒懂!)
這篇文章主要給大家介紹了關(guān)于Redis出現(xiàn)(error)NOAUTH?Authentication?required.報(bào)錯(cuò)的解決辦法,對(duì)于 這個(gè)錯(cuò)誤這通常是因?yàn)镽edis服務(wù)器需要密碼進(jìn)行身份驗(yàn)證,但客戶端沒(méi)有提供正確的身份驗(yàn)證信息導(dǎo)致的,需要的朋友可以參考下2024-03-03CentOS系統(tǒng)安裝Redis及Redis的PHP擴(kuò)展詳解
這篇文章主要介紹了CentOS系統(tǒng)下安裝Redis數(shù)據(jù)的教程,以及詳解了Redis數(shù)據(jù)庫(kù)的PHP擴(kuò)展,文中介紹的很詳細(xì),相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-12-12Springboot/Springcloud項(xiàng)目集成redis進(jìn)行存取的過(guò)程解析
大家都知道Redis支持五種數(shù)據(jù)類(lèi)型:string(字符串),hash(哈希),list(列表),set(集合),zset(sorted set:有序集合),本文重點(diǎn)給大家介紹Springboot/Springcloud項(xiàng)目集成redis進(jìn)行存取的過(guò)程,需要的朋友參考下吧2021-12-12Redis數(shù)據(jù)過(guò)期策略的實(shí)現(xiàn)詳解
最近項(xiàng)目當(dāng)中遇到一個(gè)需求場(chǎng)景,需要清空一些存放在Redis的數(shù)據(jù),本文對(duì)Redis的過(guò)期機(jī)制簡(jiǎn)單的講解一下,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09