RedisCache.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Jenner
  5. * Date: 2015/8/20
  6. * Time: 15:14
  7. */
  8. namespace Jenner\SimpleFork\Cache;
  9. /**
  10. * redis cache
  11. *
  12. * @package Jenner\SimpleFork\Cache
  13. */
  14. class RedisCache implements CacheInterface
  15. {
  16. /**
  17. * @var \Redis
  18. */
  19. protected $redis;
  20. protected $prefix;
  21. /**
  22. * @param string $host
  23. * @param int $port
  24. * @param int $database
  25. * @param string $prefix
  26. */
  27. public function __construct(
  28. $host = '127.0.0.1',
  29. $port = 6379,
  30. $database = 0,
  31. $prefix = 'simple-fork'
  32. )
  33. {
  34. $this->redis = new \Redis();
  35. $connection_result = $this->redis->connect($host, $port);
  36. if (!$connection_result) {
  37. throw new \RuntimeException('can not connect to the redis server');
  38. }
  39. if ($database != 0) {
  40. $select_result = $this->redis->select($database);
  41. if (!$select_result) {
  42. throw new \RuntimeException('can not select the database');
  43. }
  44. }
  45. if (empty($prefix)) {
  46. throw new \InvalidArgumentException('prefix can not be empty');
  47. }
  48. $this->prefix = $prefix;
  49. }
  50. /**
  51. * close redis connection
  52. */
  53. public function __destruct()
  54. {
  55. $this->close();
  56. }
  57. /**
  58. * close the connection
  59. */
  60. public function close()
  61. {
  62. $this->redis->close();
  63. }
  64. /**
  65. * get var
  66. *
  67. * @param $key
  68. * @param null $default
  69. * @return bool|string|null
  70. */
  71. public function get($key, $default = null)
  72. {
  73. $result = $this->redis->hGet($this->prefix, $key);
  74. if ($result !== false) return $result;
  75. return $default;
  76. }
  77. /**
  78. * set var
  79. *
  80. * @param $key
  81. * @param null $value
  82. * @return boolean
  83. */
  84. public function set($key, $value)
  85. {
  86. return $this->redis->hSet($this->prefix, $key, $value);
  87. }
  88. /**
  89. * has var ?
  90. *
  91. * @param $key
  92. * @return bool
  93. */
  94. public function has($key)
  95. {
  96. return $this->redis->hExists($this->prefix, $key);
  97. }
  98. /**
  99. * delete var
  100. *
  101. * @param $key
  102. * @return bool
  103. */
  104. public function delete($key)
  105. {
  106. if ($this->redis->hDel($this->prefix, $key) > 0) {
  107. return true;
  108. }
  109. return false;
  110. }
  111. }