| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <?php
- namespace PhpLife\Frame\Library;
- /**
- * Redis连接
- */
- class Redis extends \PhpLife\Frame\Library
- {
- protected $exception;
- public function getLastException()
- {
- return $this->exception;
- }
- /**
- * 获取redis连接池
- * @param bool $isMaster
- * @return \Redis
- */
- public function getConnection($isMaster = false)
- {
- static $pool = array();
- $cacheName = $this->getFlag($isMaster);
- if (!isset($pool[$cacheName]) || $pool[$cacheName] == false) {
- $cfg = $this->getConfig();
- if ($isMaster) {
- $cfg = $cfg['master'];
- } else {
- $cfg = $cfg['slave_list'][array_rand($cfg['slave_list'])];
- }
- $pool[$cacheName] = $this->connect($cfg);
- }
- return $pool[$cacheName];
- }
- /**
- * 连接Redis
- * @param $cfg
- * @return \Redis
- * @throws \Exception
- */
- protected function connect($cfg)
- {
- try {
- $redis = new \Redis();
- if (isset($cfg['pconnect']) && $cfg['pconnect'] == 1) {
- $redis->pconnect($cfg['host'], $cfg['port'], $cfg['timeout']);
- } else {
- $redis->connect($cfg['host'], $cfg['port'], $cfg['timeout']);
- }
- if (isset($cfg['password']) && $cfg['password']) {
- $redis->auth($cfg['password']);
- }
- } catch (\Exception $ex) {
- $this->exception = $ex;
- $message = "Redis connection failed : [" . $cfg['host'] . ';' . $cfg['port'] . ']';
- throw new \Exception($message, 90301);
- }
- return $redis;
- }
- }
|