新聞中心
Redis是一個(gè)開源的使用ANSI C語言開發(fā)的key-value數(shù)據(jù)庫,它的速度非??欤С纸俜N數(shù)據(jù)結(jié)構(gòu),可以執(zhí)行復(fù)雜的內(nèi)存數(shù)據(jù)庫操作,比如典型的讀寫鎖機(jī)制,可以用來設(shè)置操作超時(shí)時(shí)間。

創(chuàng)新互聯(lián)建站是專業(yè)的南皮網(wǎng)站建設(shè)公司,南皮接單;提供做網(wǎng)站、網(wǎng)站制作,網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行南皮網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
利用Redis實(shí)現(xiàn)鎖機(jī)制非常簡單,首先要定義一個(gè)自旋鎖,用來設(shè)置當(dāng)前操作是否可以在固定時(shí)間內(nèi)完成,通過調(diào)用Redis指令來實(shí)現(xiàn):
“`language
String lockKey = “l(fā)ock”;
//Setting maximum wt time to 10 seconds
Long timeOut = 10L;
//Setting the time when the lock is set
Long lockTime = System.currentTimeMillis() + timeOut;
//Using Redis command to set an ex-time for the lockKey
jedis.set(lockKey, lockTime +””);
從上面的代碼我們可以看到,我們將指定的lockKey值設(shè)置為當(dāng)前操作的絕對(duì)超時(shí)時(shí)間,如果此時(shí)此刻沒有其他線程對(duì)lockKey設(shè)置對(duì)應(yīng)的值,那么這個(gè)操作就得以執(zhí)行,并且只能在絕對(duì)的超時(shí)時(shí)間內(nèi)執(zhí)行。
下面可以定義一個(gè)自旋鎖方法用來判斷超時(shí)時(shí)間,假設(shè)我們?cè)O(shè)置的最長等待時(shí)間為10秒,超時(shí)時(shí)間為10秒,過了10秒之后線程可以獲取這個(gè)鎖:
```language
public boolean spinLock(String key, Long expireTime){
Long lockTime = System.currentTimeMillis() + expireTime;
if(jedis.setnx(key, lockTime+"")>0){
return true;
}
String redisLockTimeStr = jedis.get(key);
//Check if the lock has expired, then update the lock
if(Long.parseLong(redisLockTimeStr)
//When multiple threads come in at the same time, it will be judged first
//If someone else has set the value, then set the lock to an old value
String oldLockTimeStr = jedis.getSet(key, lockTime+"");
if(oldLockTimeStr != null && oldLockTimeStr.equals(redisLockTimeStr)){
//Judge if there is an unequal operation
return true;
}
}
return false;
}
從上面的代碼可以看出,如果超時(shí)時(shí)間設(shè)置正確,則可以有效控制擁有鎖的線程可以在合理的時(shí)間內(nèi)完成操作,如果超時(shí)時(shí)間設(shè)置太短,則可能發(fā)生死鎖現(xiàn)象,造成系統(tǒng)假死,影響系統(tǒng)的正常使用,因此需要選擇合理的超時(shí)時(shí)間,才能使系統(tǒng)良好的運(yùn)行。
香港服務(wù)器選創(chuàng)新互聯(lián),2H2G首月10元開通。
創(chuàng)新互聯(lián)(www.cdcxhl.com)互聯(lián)網(wǎng)服務(wù)提供商,擁有超過10年的服務(wù)器租用、服務(wù)器托管、云服務(wù)器、虛擬主機(jī)、網(wǎng)站系統(tǒng)開發(fā)經(jīng)驗(yàn)。專業(yè)提供云主機(jī)、虛擬主機(jī)、域名注冊(cè)、VPS主機(jī)、云服務(wù)器、香港云服務(wù)器、免備案服務(wù)器等。
分享名稱:利用Redis鎖機(jī)制設(shè)置超時(shí)時(shí)間(redis鎖設(shè)置超時(shí)時(shí)間)
轉(zhuǎn)載來源:http://fisionsoft.com.cn/article/coopcpi.html


咨詢
建站咨詢
