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
|
|
|
|
8
|
|
|
namespace yii\mutex; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\InvalidConfigException; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* MysqlMutex implements mutex "lock" mechanism via MySQL locks. |
15
|
|
|
* |
16
|
|
|
* Application configuration example: |
17
|
|
|
* |
18
|
|
|
* ``` |
19
|
|
|
* [ |
20
|
|
|
* 'components' => [ |
21
|
|
|
* 'db' => [ |
22
|
|
|
* 'class' => 'yii\db\Connection', |
23
|
|
|
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
24
|
|
|
* ] |
25
|
|
|
* 'mutex' => [ |
26
|
|
|
* 'class' => 'yii\mutex\MysqlMutex', |
27
|
|
|
* ], |
28
|
|
|
* ], |
29
|
|
|
* ] |
30
|
|
|
* ``` |
31
|
|
|
* |
32
|
|
|
* @see Mutex |
33
|
|
|
* |
34
|
|
|
* @author resurtm <[email protected]> |
35
|
|
|
* @since 2.0 |
36
|
|
|
*/ |
37
|
|
|
class MysqlMutex extends DbMutex |
38
|
|
|
{ |
39
|
|
|
/** |
40
|
|
|
* Initializes MySQL specific mutex component implementation. |
41
|
|
|
* @throws InvalidConfigException if [[db]] is not MySQL connection. |
42
|
|
|
*/ |
43
|
|
|
public function init() |
44
|
|
|
{ |
45
|
|
|
parent::init(); |
46
|
|
|
if ($this->db->driverName !== 'mysql') { |
47
|
|
|
throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.'); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Acquires lock by given name. |
53
|
|
|
* @param string $name of the lock to be acquired. |
54
|
|
|
* @param int $timeout to wait for lock to become released. |
55
|
|
|
* @return bool acquiring result. |
56
|
|
|
* @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock |
57
|
|
|
*/ |
58
|
|
|
protected function acquireLock($name, $timeout = 0) |
59
|
|
|
{ |
60
|
|
|
return (bool) $this->db |
61
|
|
|
->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout]) |
62
|
|
|
->queryScalar(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Releases lock by given name. |
67
|
|
|
* @param string $name of the lock to be released. |
68
|
|
|
* @return bool release result. |
69
|
|
|
* @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock |
70
|
|
|
*/ |
71
|
|
|
protected function releaseLock($name) |
72
|
|
|
{ |
73
|
|
|
return (bool) $this->db |
74
|
|
|
->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name]) |
75
|
|
|
->queryScalar(); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|