一、普通Redis實例化類:
class MyRedis { private $redis; public function __construct($host = '121.41.88.209', $port = 63789) { $this->redis = new Redis(); $this->redis->connect($host, $port); } public function expire($key = null, $time = 0) { return $this->redis->expire($key, $time); } public function psubscribe($patterns = array(), $callback) { $this->redis->psubscribe($patterns, $callback); } public function setOption() { $this->redis->setOption(\Redis::OPT_READ_TIMEOUT,-1); } }
二、單例模式Redis實例化類:
<?php /** * Created by PhpStorm. * User: Tinywan * Date: 2016/7/3 * Time: 9:26 * Mail: Overcome.wan@Gmail.com * Singleton instance */ namespace Org\Util; class RedisInstance { /** * 類對象實例數組,共有靜態變量 * @var null */ private static $_instance; /** * 數據庫連接資源句柄 * @var */ private static $_connectSource; /** * 私有化構造函數,防止類外實例化 * RedisConnect constructor. */ private function __construct() { } /** * 單例方法,用於訪問實例的公共的靜態方法 * @return \Redis * @static */ public static function getInstance() { if (!(static::$_instance instanceof \Redis)) { static::$_instance = new \Redis(); self::getInstance()->connect(C('MASTER.HOST'), C('MASTER.PORT'), C('MASTER.TIMEOUT')); } return static::$_instance; } /** * Redis數據庫是否連接成功 * @return bool|string */ public static function connect() { // 如果連接資源不存在,則進行資源連接 if (!self::$_connectSource) { //@return bool TRUE on success, FALSE on error. self::$_connectSource = self::getInstance()->connect(C('MASTER.HOST'), C('MASTER.PORT'), C('MASTER.TIMEOUT')); // 沒有資源返回 if (!self::$_connectSource) { return 'Redis Server Connection Fail'; } } return self::$_connectSource; } /** * 私有化克隆函數,防止類外克隆對象 */ private function __clone() { // TODO: Implement __clone() method. } /** * @return \Redis * @static */ public static function test() { return 'test'; }