Redis.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace PhpLife\Frame\Library;
  3. /**
  4. * Redis连接
  5. */
  6. class Redis extends \PhpLife\Frame\Library
  7. {
  8. protected $exception;
  9. public function getLastException()
  10. {
  11. return $this->exception;
  12. }
  13. /**
  14. * 获取redis连接池
  15. * @param bool $isMaster
  16. * @return \Redis
  17. */
  18. public function getConnection($isMaster = false)
  19. {
  20. static $pool = array();
  21. $cacheName = $this->getFlag($isMaster);
  22. if (!isset($pool[$cacheName]) || $pool[$cacheName] == false) {
  23. $cfg = $this->getConfig();
  24. if ($isMaster) {
  25. $cfg = $cfg['master'];
  26. } else {
  27. $cfg = $cfg['slave_list'][array_rand($cfg['slave_list'])];
  28. }
  29. $pool[$cacheName] = $this->connect($cfg);
  30. }
  31. return $pool[$cacheName];
  32. }
  33. /**
  34. * 连接Redis
  35. * @param $cfg
  36. * @return \Redis
  37. * @throws \Exception
  38. */
  39. protected function connect($cfg)
  40. {
  41. try {
  42. $redis = new \Redis();
  43. if (isset($cfg['pconnect']) && $cfg['pconnect'] == 1) {
  44. $redis->pconnect($cfg['host'], $cfg['port'], $cfg['timeout']);
  45. } else {
  46. $redis->connect($cfg['host'], $cfg['port'], $cfg['timeout']);
  47. }
  48. if (isset($cfg['password']) && $cfg['password']) {
  49. $redis->auth($cfg['password']);
  50. }
  51. } catch (\Exception $ex) {
  52. $this->exception = $ex;
  53. $message = "Redis connection failed : [" . $cfg['host'] . ';' . $cfg['port'] . ']';
  54. throw new \Exception($message, 90301);
  55. }
  56. return $redis;
  57. }
  58. }