Redis.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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' => $host['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->_default_policy['life_time'];
  46. try {
  47. $this->redis->hMset($id, $data);
  48. if ($policy['lift_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 get($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 remove($id)
  69. {
  70. if ($this->redis->exists($id)) {
  71. return $this->redis->delete($id);
  72. }
  73. }
  74. /**
  75. * 清除当前db的所有数据
  76. */
  77. public function clean()
  78. {
  79. $this->redis->flushdb();
  80. }
  81. }