您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在scala中使用redis實(shí)現(xiàn)分布式鎖,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
首先實(shí)現(xiàn)工具類
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類
package utils import com.redis.RedisClientPool /** * */ object CacheManager { val redisClientPool = "dev".equalsIgnoreCase(System.getenv("SCALA_ENV")) match { //開發(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)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。