Redis.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Qii\Cache;
  3. \Qii\Autoloader\Import::requires(array(dirname(__FILE__) . DS . 'Redis/Client.php', dirname(__FILE__) . DS . 'Redis/Cluster.php'));
  4. /**
  5. * PHP 操作 redis
  6. * @author Jinhui.Zhu
  7. *
  8. */
  9. class Redis implements Intf
  10. {
  11. const VERSION = '1.2';
  12. public $redis;
  13. protected $policy = array(
  14. /**
  15. * 缓存服务器配置,参看$_default_server
  16. * 允许多个缓存服务器
  17. */
  18. 'servers' => array(['host' => '127.0.0.1', 'port' => '6379']),
  19. /**
  20. * 缓存有效时间
  21. *
  22. * 如果设置为 0 表示缓存永不过期
  23. */
  24. 'life_time' => 900
  25. );
  26. public function __construct(array $policy = null)
  27. {
  28. if (!extension_loaded('redis')) {
  29. throw new \Qii\Exceptions\MethodNotFound(\Qii::i(1006), __LINE__);
  30. }
  31. if (!empty($policy)) {
  32. $this->policy = array_merge($this->policy, $policy);
  33. }
  34. $redisServer = array();
  35. foreach ($this->policy['servers'] AS $value) {
  36. $redisServer[] = array('host' => $value['host'], 'port' => $value['port']);
  37. }
  38. $this->redis = new \Qii\Cache\Redis\Cluster($redisServer, 128);
  39. }
  40. /**
  41. * 保存指定key的数据
  42. */
  43. public function set($id, $data, array $policy = null)
  44. {
  45. if (!isset($policy['life_time'])) $policy['life_time'] = $this->policy['life_time'];
  46. try {
  47. $this->redis->hMset($id, $data);
  48. if (isset($policy['life_time']) && $policy['life_time'] > 0) {
  49. $this->redis->setTimeout($id, $policy['life_time']);
  50. }
  51. } catch (\CredisException $e) {
  52. throw new \Qii\Exceptions\Errors(\Qii::i(-1, $e->getMessage()), __LINE__);
  53. }
  54. }
  55. /**
  56. * 获取指定key的数据
  57. */
  58. public function hGet($id)
  59. {
  60. if ($this->redis->exists($id)) {
  61. return $this->redis->hGetAll($id);
  62. }
  63. return null;
  64. }
  65. /**
  66. * 获取指定key的数据
  67. */
  68. public function get($id)
  69. {
  70. if ($this->redis->exists($id)) {
  71. return $this->redis->get($id);
  72. }
  73. return null;
  74. }
  75. /**
  76. * 删除指定key的数据
  77. */
  78. public function remove($id)
  79. {
  80. if ($this->redis->exists($id)) {
  81. return $this->redis->delete($id);
  82. }
  83. }
  84. /**
  85. * 清除当前db的所有数据
  86. */
  87. public function clean()
  88. {
  89. $this->redis->flushdb();
  90. }
  91. public function __call($method, $args)
  92. {
  93. return call_user_func_array(array($this->redis, $method), $args);
  94. }
  95. }