You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MysqlMutex.php 2.1KB

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