寫一個Redis封裝類

來源:互聯網
上載者:User

標籤:

打算自己封裝一個Redis操作類,方便使用,且有一定log記錄。
Redis的封裝思路:
基於Redis類進一步封裝


一般屬性

單例 (配置參數從設定檔中讀取還是寫死?考慮多配置之間切換)

常規操作根據業務單獨處理。(注意健壯性和容錯)

目的不同,可能做的封裝也同。
我們要基於業務做一些抽象程度較低的封裝,也會根據需要,做一些tool層級的高抽象的封裝。如果抽象的足夠高,可以讓通用性變得更好。
這次封裝Redis,我先做一個通用性的Redis操作類,先僅作最基本的一些操作。

代碼如下:

<?php/** * Created by PhpStorm. * User: freephp * Date: 2016/1/4 * Time: 11:09 */class MyRedis extends Redis {    public static $instance = null;  // 單例對象    public $isConnect = false; // 判斷redis是否連結成功    public $connectMsg = ‘‘; // redis連結資訊    public $date = null; // log記錄日期    private $config = [        //主(master)伺服器        ‘master‘ => [            ‘hostname‘ => ‘192.168.1.223‘,            ‘password‘ => ‘sewerew‘,            ‘port‘ => ‘6379‘,            ‘timeout‘ => ‘5‘,        ],        //從(slave)伺服器        ‘slave‘ => [            ‘hostname‘ => ‘192.168.1.230‘,            ‘password‘ => ‘qweqq‘,            ‘port‘ => ‘6379‘,            ‘timeout‘ => ‘5‘,        ]    ];    function __construct($params = array()) {        parent::__construct();        $serverArray = $this->config;        //組裝參數        $hostname = $serverArray[‘master‘][‘hostname‘]; //串連地址        $password = $serverArray[‘master‘][‘password‘]; //密碼        $port = $serverArray[‘master‘][‘port‘]; //連接埠        $timeout = $serverArray[‘master‘][‘timeout‘]; //逾時        //選擇使用者指定的主機和資料庫        if (isset($params[‘redis‘]) && array_key_exists($params[‘redis‘], $serverArray)) {            $hostname = $serverArray[$params[‘redis‘]][‘hostname‘]; //串連地址            $password = $serverArray[$params[‘redis‘]][‘password‘]; //密碼            $port = $serverArray[$params[‘redis‘]][‘port‘]; //連接埠            $timeout = $serverArray[$params[‘redis‘]][‘timeout‘]; //逾時        }        $this->date = date(‘Y-m-d‘, time());        $this->_connect($hostname, $port, $timeout, $password);    }    /**     *  串連資料庫     *     * @param string $hostname  主機地址     * @param int    $port      redis連接埠     * @param int    $timeout   逾時時間預設30s     * @param string $password  驗證密碼     * @param bool   $isPConnect  是否長串連:預設false非長串連     * @return bool               傳回值:成功返回true,失敗false     */    private function _connect($hostname, $port = 6379, $timeout = 5, $password = ‘‘, $isPConnect = false) {        //開始串連資料庫        try {            if ($isPConnect == false) {                $status = $this->connect($hostname, $port, $timeout);            } else {                $status = $this->pconnect($hostname, $port, $timeout);            }            if (!$status) {                error_log(date(‘Y-m-d H:i:s‘) . ":" . ‘redis connect error‘ . "\t",3, "./application/logs/redis-error-{$this->date}.log");                return $this->response(false, ‘redis connect error‘);            }        } catch (Exception $e) {            error_log(date(‘Y-m-d H:i:s‘) . ":" . $e->getMessage() . "\t",3, "./application/logs/redis-error-{$this->date}.log");            return $this->response(false, $e->getMessage());        }        //驗證密碼        if ($password && !$this->auth($password)) {            error_log(date(‘Y-m-d H:i:s‘) . ":" . ‘redis password error‘ . "\t",3, "./application/logs/redis-error-{$this->date}.log");            return $this->response(false, ‘redis password error‘);        }        return $this->response(true, ‘redis connect success‘);    }    public static function getInstance($params = array(), $flag = false) {        if (!(self::$instance instanceof self) || $flag) {            self::$instance = new self($params = array());        }        return self::$instance;    }    /**     * 返回訊息     *     * @param  bool   $status   狀態     * @param  string $msg      訊息     * @return void     */    private function response($status = false, $msg = ‘‘) {        $this->isConnect = $status; //判斷redis是否串連成功        $this->connectMsg = $msg;  //串連redis的訊息通知        return $status;    }}
// 調用
$myredis = new MyRedis();var_dump($myredis->connectMsg);die();

 我們基於更詳細業務做的其他封裝類可以使用這個MyRedis作為一個注入類,多用組合,實現解耦。

寫一個Redis封裝類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.