基於redis實現分布式鎖

2021-09-29 18:59:22 字數 1349 閱讀 4016

四個同時都去切換表 + 1 的操作是不可以的,他們要先從 redis 獲取一把鎖,沒有獲取到鎖的就直接退出,等待下一次定時任務的排程。拿到了鎖的就去執行切換當前分表的操作

獲取鎖 和 釋放鎖 的關鍵**如下所示:

/**

* set the string value as value of the key. the string can't be longer than 1073741824 bytes (1

* gb).

* @param key

* @param value

* @param n*** nx|xx, nx -- only set the key if it does not already exist. xx -- only set the key

* if it already exist.

* @param expx ex|px, expire time units: ex = seconds; px = milliseconds

* @param time expire time in the units ofexpx* @return status code reply

* @auther daleyzou

*/public boolean set(string key, string value, string n***, string expx,

long time) else

} catch (exception e) finally

return false;

}/***

* @description: 解鎖時比較值是否相等

* @date: 22:33 2019/7/22

* @param: key

* @param: request value

* @return: boolean

*/public boolean unlock(string key,string request)else

} catch (exception e) finally

return false;

}

private static final string set_if_not_exist = "nx";

private static final string set_with_expire_time = "ex";

if (myjedisservice.set(refreshmaxid, value, set_if_not_exist, set_with_expire_time, expiretime))else

參考鏈結:

基於Redis實現分布式鎖

分布式鎖的基本功能 1.同一時刻只能存在乙個鎖 2.需要解決意外死鎖問題,也就是鎖能超時自動釋放 3.支援主動釋放鎖 分布式鎖解決什麼問題 多程序併發執行任務時,需要保證任務的有序性或者唯一性 準備 redis版本 2.6 redis是主從 sentinel模式 為了高可用 原理 redis2.6之...

基於Redis實現分布式鎖

之前專案中使用redis鎖實現秒殺等一些併發業務,在這裡整理一下基於redis實現分布式鎖的簡單入門例項,記錄一下,便於以後檢視 學習。springboot整合redisson分布式鎖 1 簡介 在分布式系統中存在併發場景,為了解決這一問題,基於redis鎖一定程度可以解決這一問題,但是也有缺點,如...

基於redis實現分布式鎖

實現方式 具備條件 確保鎖可用,必須要滿足一下幾個條件 1 互斥性,任意時刻只有乙個使用者能持有鎖 2 不會產生死鎖,假設某個使用者在持有鎖的期間由於服務崩潰或者其他原因沒有主動釋放鎖,也能保證後續其他使用者可以加鎖 3 加鎖和解鎖必須是同一使用者,b使用者無法解除a使用者加的鎖 實現 1 引入je...