Redis.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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('127.0.0.1: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. $host = explode(':', $value);
  37. $redisServer[] = array('host' => $host[0], 'port' => $host[1]);
  38. }
  39. $this->redis = new \Redis\Credis\Cluster($redisServer, 128);
  40. }
  41. /**
  42. * 保存指定key的数据
  43. */
  44. public function set($id, $data, array $policy = null)
  45. {
  46. if (!isset($policy['life_time'])) $policy['life_time'] = $this->_default_policy['life_time'];
  47. try {
  48. $this->redis->hMset($id, $data);
  49. if ($policy['lift_time'] > 0) {
  50. $this->redis->setTimeout($id, $policy['life_time']);
  51. }
  52. } catch (\CredisException $e) {
  53. throw new Errors(\Qii::i(-1, $e->getMessage()), __LINE__);
  54. }
  55. }
  56. /**
  57. * 获取指定key的数据
  58. */
  59. public function get($id)
  60. {
  61. if ($this->redis->exists($id)) {
  62. return $this->redis->hGetAll($id);
  63. }
  64. return null;
  65. }
  66. /**
  67. * 删除指定key的数据
  68. */
  69. public function remove($id)
  70. {
  71. if ($this->redis->exists($id)) {
  72. return $this->redis->delete($id);
  73. }
  74. }
  75. /**
  76. * 清除当前db的所有数据
  77. */
  78. public function clean()
  79. {
  80. $this->redis->flushdb();
  81. }
  82. }