Mutex.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\redis;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\di\Instance;
  11. /**
  12. * Redis Mutex implements a mutex component using [redis](http://redis.io/) as the storage medium.
  13. *
  14. * Redis Mutex requires redis version 2.6.12 or higher to work properly.
  15. *
  16. * It needs to be configured with a redis [[Connection]] that is also configured as an application component.
  17. * By default it will use the `redis` application component.
  18. *
  19. * To use redis Mutex as the application component, configure the application as follows:
  20. *
  21. * ```php
  22. * [
  23. * 'components' => [
  24. * 'mutex' => [
  25. * 'class' => 'yii\redis\Mutex',
  26. * 'redis' => [
  27. * 'hostname' => 'localhost',
  28. * 'port' => 6379,
  29. * 'database' => 0,
  30. * ]
  31. * ],
  32. * ],
  33. * ]
  34. * ```
  35. *
  36. * Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
  37. *
  38. * ```php
  39. * [
  40. * 'components' => [
  41. * 'mutex' => [
  42. * 'class' => 'yii\redis\Mutex',
  43. * // 'redis' => 'redis' // id of the connection application component
  44. * ],
  45. * ],
  46. * ]
  47. * ```
  48. *
  49. * @see \yii\mutex\Mutex
  50. * @see http://redis.io/topics/distlock
  51. *
  52. * @author Sergey Makinen <sergey@makinen.ru>
  53. * @author Alexander Zhuravlev <axelhex@gmail.com>
  54. * @since 2.0.6
  55. */
  56. class Mutex extends \yii\mutex\Mutex
  57. {
  58. /**
  59. * @var int the number of seconds in which the lock will be auto released.
  60. */
  61. public $expire = 30;
  62. /**
  63. * @var string a string prefixed to every cache key so that it is unique. If not set,
  64. * it will use a prefix generated from [[Application::id]]. You may set this property to be an empty string
  65. * if you don't want to use key prefix. It is recommended that you explicitly set this property to some
  66. * static value if the cached data needs to be shared among multiple applications.
  67. */
  68. public $keyPrefix;
  69. /**
  70. * @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
  71. * This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
  72. * redis connection as an application component.
  73. * After the Mutex object is created, if you want to change this property, you should only assign it
  74. * with a Redis [[Connection]] object.
  75. */
  76. public $redis = 'redis';
  77. /**
  78. * @var array Redis lock values. Used to be safe that only a lock owner can release it.
  79. */
  80. private $_lockValues = [];
  81. /**
  82. * Initializes the redis Mutex component.
  83. * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  84. * @throws InvalidConfigException if [[redis]] is invalid.
  85. */
  86. public function init()
  87. {
  88. parent::init();
  89. $this->redis = Instance::ensure($this->redis, Connection::className());
  90. if ($this->keyPrefix === null) {
  91. $this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
  92. }
  93. }
  94. /**
  95. * Acquires a lock by name.
  96. * @param string $name of the lock to be acquired. Must be unique.
  97. * @param int $timeout time (in seconds) to wait for lock to be released. Defaults to `0` meaning that method will return
  98. * false immediately in case lock was already acquired.
  99. * @return bool lock acquiring result.
  100. */
  101. protected function acquireLock($name, $timeout = 0)
  102. {
  103. $key = $this->calculateKey($name);
  104. $value = Yii::$app->security->generateRandomString(20);
  105. $waitTime = 0;
  106. while (!$this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)])) {
  107. $waitTime++;
  108. if ($waitTime > $timeout) {
  109. return false;
  110. }
  111. sleep(1);
  112. }
  113. $this->_lockValues[$name] = $value;
  114. return true;
  115. }
  116. /**
  117. * Releases acquired lock. This method will return `false` in case the lock was not found or Redis command failed.
  118. * @param string $name of the lock to be released. This lock must already exist.
  119. * @return bool lock release result: `false` in case named lock was not found or Redis command failed.
  120. */
  121. protected function releaseLock($name)
  122. {
  123. static $releaseLuaScript = <<<LUA
  124. if redis.call("GET",KEYS[1])==ARGV[1] then
  125. return redis.call("DEL",KEYS[1])
  126. else
  127. return 0
  128. end
  129. LUA;
  130. if (!isset($this->_lockValues[$name]) || !$this->redis->executeCommand('EVAL', [
  131. $releaseLuaScript,
  132. 1,
  133. $this->calculateKey($name),
  134. $this->_lockValues[$name]
  135. ])) {
  136. return false;
  137. } else {
  138. unset($this->_lockValues[$name]);
  139. return true;
  140. }
  141. }
  142. /**
  143. * Generates a unique key used for storing the mutex in Redis.
  144. * @param string $name mutex name.
  145. * @return string a safe cache key associated with the mutex name.
  146. */
  147. protected function calculateKey($name)
  148. {
  149. return $this->keyPrefix . md5(json_encode([__CLASS__, $name]));
  150. }
  151. }