Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.today.commons.lock
- import com.today.service.commons.help.BizHelp.withJedis
- import com.today.service.purchase.PurchaseDataSource.jedisPool
- import scala.collection.convert.ImplicitConversionsToJava._
- /**
- * Created by cjl at 2018-09-02
- * Description:
- * Changed:
- */
- object RedisLock {
- //NX -- Only set the key if it does not already exist. XX -- Only set the key if it already exist
- private val SET_IF_NOT_EXIST: String = "NX"
- //expire time units: EX = seconds; PX = milliseconds
- private val SET_WITH_EXPIRE_TIME: String = "PX"
- private val LOCK_SUCCESS: String = "OK"
- private val RELEASE_SUCCESS: Long = 1L
- /**
- * 尝试获取分布式锁
- *
- * @param lockKey 锁
- * @param requestId 请求标识
- * @param expireTime 超期时间 单位:毫秒
- * @return 是否获取成功
- */
- def tryLock(lockKey: String, requestId: String, expireTime: Long): Boolean = {
- val res = withJedis(jedisPool)( j =>
- j.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime)
- )
- res.isDefined && res.get == LOCK_SUCCESS
- }
- /**
- * 释放分布式锁
- *
- * @param lockKey 锁
- * @param requestId 请求标识 防止开别人的锁
- * @return 是否释放成功
- */
- def releaseLock(lockKey: String, requestId: String): Boolean = {
- // 原子性 eval命令执行lua代码的时候,lua代码将被当成一个命令去执行,并且直到eval命令执行完成,Redis才会执行其他命令
- val script: String = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
- val res = withJedis(jedisPool)(
- _.eval(script, List(lockKey), List(requestId))
- )
- res.isDefined && res.get == RELEASE_SUCCESS
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement