本篇文章為大家展示了如何在scala中使用redis實(shí)現(xiàn)分布式鎖,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
目前累計(jì)服務(wù)客戶上千,積累了豐富的產(chǎn)品開(kāi)發(fā)及服務(wù)經(jīng)驗(yàn)。以網(wǎng)站設(shè)計(jì)水平和技術(shù)實(shí)力,樹(shù)立企業(yè)形象,為客戶提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站策劃、網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)絡(luò)營(yíng)銷(xiāo)、VI設(shè)計(jì)、網(wǎng)站改版、漏洞修補(bǔ)等服務(wù)。成都創(chuàng)新互聯(lián)公司始終以務(wù)實(shí)、誠(chéng)信為根本,不斷創(chuàng)新和提高建站品質(zhì),通過(guò)對(duì)領(lǐng)先技術(shù)的掌握、對(duì)創(chuàng)意設(shè)計(jì)的研究、對(duì)客戶形象的視覺(jué)傳遞、對(duì)應(yīng)用系統(tǒng)的結(jié)合,為客戶提供更好的一站式互聯(lián)網(wǎng)解決方案,攜手廣大客戶,共同發(fā)展進(jìn)步。
首先實(shí)現(xiàn)工具類(lèi)
package utils import CacheManager /** * redis分布式鎖 */ object RedisTool { //加鎖是否成功標(biāo)志 val LOCK_SUCCESS:String = "OK" //即當(dāng)key不存在時(shí),我們進(jìn)行set操作;若key已經(jīng)存在,則不做任何操作; val SET_IF_NOT_EXIST:String = "NX" //意思是我們要給這個(gè)key加一個(gè)過(guò)期的設(shè)置,具體時(shí)間由第五個(gè)參數(shù)決定。 val SET_WITH_EXPIRE_TIME:String = "PX" val RELEASE_SUCCESS:String = "1" /** * * @param lockKey 鎖 * @param requestId 請(qǐng)求標(biāo)識(shí) * @param expireTime 超期時(shí)間 * @param isPersist 臨時(shí)緩存或者永久緩存 */ def tryGetDistributedLock(lockKey:String, requestId:String, expireTime:Int,isPersist:Boolean=false){ CacheManager.redisClientPool.withClient( client => { //val redisKeyPrefix = CacheManager.getRedisKeyPrefix(isPersist) client.select(CacheManager.redisDBNum) val result = client.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime) var flag = false if(LOCK_SUCCESS == result){ flag = true } flag } ) } /** *釋放分布式鎖 * @param lockKey 鎖 * @param requestId 請(qǐng)求標(biāo)識(shí) * @param expireTime 超期時(shí)間 * @param isPersist 臨時(shí)緩存或者永久緩存 * @return */ def releaseDistributedLock(lockKey:String, requestId:String,expireTime: Int = 10,isPersist:Boolean=false) ={ CacheManager.redisClientPool.withClient( client => { val redisKeyPrefix = CacheManager.getRedisKeyPrefix(isPersist) client.select(CacheManager.redisDBNum) //lua腳本也是單例模式,同樣也可以保證同一時(shí)刻只有一個(gè)線程執(zhí)行腳本 val lua = s""" |local current = redis.call('incrBy',KEYS[1],ARGV[1]); |if current == tonumber(ARGV[1]) then | local t = redis.call('ttl',KEYS[1]); | if t == -1 then | redis.call('expire',KEYS[1],ARGV[2]) | end; |end; |return current; """.stripMargin val code = client.scriptLoad(lua).get val ret = client.evalSHA(code, List(redisKeyPrefix + lockKey),List(requestId,expireTime)) val result = ret.get.asInstanceOf[Object].toString var flag = false if(result == RELEASE_SUCCESS){ flag = true } flag } ) } }
2、實(shí)現(xiàn)CacheManager類(lèi)
package utils import com.redis.RedisClientPool /** * */ object CacheManager { val redisClientPool = "dev".equalsIgnoreCase(System.getenv("SCALA_ENV")) match { //開(kāi)發(fā)環(huán)境 case true => new RedisClientPool("127.0.0.1", 6379) //其他環(huán)境 case false => new RedisClientPool("10.180.x.y", 6379, 8, 0, Some("root")) } val redisDBNum = 10 def getRedisKeyPrefix(isPersist:Boolean) ={ if(isPersist){ //永久緩存前綴 "persist_" }else{ //臨時(shí)緩存前綴 "tmp_" } } }
3、調(diào)用鎖操作
def updateTableInfo(param:String) = { var resMap = Map[String,Any]() val lockKey = "mdms.MdmsUtils.updateTableInfo" //val requestId = UUID.randomUUID().toString().replace("-", "").toUpperCase() val flag = RedisTool.releaseDistributedLock(lockKey, "1") if(flag){ try{ //執(zhí)行你的操作 resMap = Map("code" -> 200 ,"msg" -> "成功") }catch { case e:Exception => { e.printStackTrace() resMap = Map("code" -> 200101 ,"msg" -> "執(zhí)行失敗") } } }else{ resMap = Map("code" -> 200102 ,"msg" -> "操作沖突,已經(jīng)被其他人捷足先登啦。") } resMap }
上述內(nèi)容就是如何在scala中使用redis實(shí)現(xiàn)分布式鎖,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。