<?php

namespace Heanup\Frame\Library;

/**
 * Redis连接
 */
class Redis extends \Heanup\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;
    }
}
