Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package com.today.commons.lock
  2.  
  3. import com.today.service.commons.help.BizHelp.withJedis
  4. import com.today.service.purchase.PurchaseDataSource.jedisPool
  5.  
  6. import scala.collection.convert.ImplicitConversionsToJava._
  7.  
  8. /**
  9. * Created by cjl at 2018-09-02
  10. * Description:
  11. * Changed:
  12. */
  13. object RedisLock {
  14.  
  15. //NX -- Only set the key if it does not already exist. XX -- Only set the key if it already exist
  16. private val SET_IF_NOT_EXIST: String = "NX"
  17. //expire time units: EX = seconds; PX = milliseconds
  18. private val SET_WITH_EXPIRE_TIME: String = "PX"
  19.  
  20. private val LOCK_SUCCESS: String = "OK"
  21. private val RELEASE_SUCCESS: Long = 1L
  22.  
  23. /**
  24. * 尝试获取分布式锁
  25. *
  26. * @param lockKey 锁
  27. * @param requestId 请求标识
  28. * @param expireTime 超期时间 单位:毫秒
  29. * @return 是否获取成功
  30. */
  31. def tryLock(lockKey: String, requestId: String, expireTime: Long): Boolean = {
  32. val res = withJedis(jedisPool)( j =>
  33. j.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime)
  34. )
  35. res.isDefined && res.get == LOCK_SUCCESS
  36. }
  37.  
  38. /**
  39. * 释放分布式锁
  40. *
  41. * @param lockKey 锁
  42. * @param requestId 请求标识 防止开别人的锁
  43. * @return 是否释放成功
  44. */
  45. def releaseLock(lockKey: String, requestId: String): Boolean = {
  46. // 原子性 eval命令执行lua代码的时候,lua代码将被当成一个命令去执行,并且直到eval命令执行完成,Redis才会执行其他命令
  47. val script: String = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
  48. val res = withJedis(jedisPool)(
  49. _.eval(script, List(lockKey), List(requestId))
  50. )
  51. res.isDefined && res.get == RELEASE_SUCCESS
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement