redis封裝類

class Redis
{
    public $redisObj = null;//redis實例化時靜態變量

    static protected $instance;
    protected $sn;
    protected $index;

    public function __construct($options = [])
    {
        $host = trim(isset($options["host"]) ? $options["host"] : '127.0.0.1');
        $port = trim(isset($options["port"]) ? $options["port"] : 6379);
        $auth = trim(isset($options["auth"]) ? $options["auth"] : "password");
        $index = trim(isset($options["index"]) ? $options["index"] : 0);
        if (!is_integer($index) && $index > 16) {
            $index = 0;
        }
        $sn = md5("{$host}{$port}{$auth}{$index}");
        $this->sn = $sn;
        if (!isset($this->redisObj[$this->sn])) {
            $this->redisObj[$this->sn] = new \Redis();
            $this->redisObj[$this->sn]->connect($host, $port);
            $this->redisObj[$this->sn]->auth($auth);
            $this->redisObj[$this->sn]->select($index);
        }
        $this->redisObj[$this->sn]->sn = $sn;
        $this->index = $index;
        return;
    }

    /**
     * Power: Mikkle
     * Email:776329498@qq.com
     * @param array $options
     * @return Redis
     */
    public static function instance($options = [])
    {
        return new Redis($options);
    }


    public function setExpire($key, $time = 0)
    {

        if (!$key) {
            return false;
        }
        switch (true) {
            case ($time == 0):
                return $this->redisObj[$this->sn]->expire($key, 0);
                break;
            case ($time > time()):
                $this->redisObj[$this->sn]->expireAt($key, $time);
                break;
            default:
                return $this->redisObj[$this->sn]->expire($key, $time);
        }
    }


    /*------------------------------------start 1.string結構----------------------------------------------------*/
    /**
     * 增,設置值  構建一個字符串
     * @param string $key KEY名稱
     * @param string $value 設置值
     * @param int $timeOut 時間  0表示無過時時間
     * @return true【老是返回true】
     */
    public function set($key, $value, $timeOut = 0)
    {
        $setRes = $this->redisObj[$this->sn]->set($key, $value);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        return $setRes;
    }

    /**
     * 查,獲取 某鍵對應的值,不存在返回false
     * @param $key ,鍵值
     * @return bool|string ,查詢成功返回信息,失敗返回false
     */
    public function get($key)
    {
        $setRes = $this->redisObj[$this->sn]->get($key);//不存在返回false
        if ($setRes === 'false') {
            return false;
        }
        return $setRes;
    }
    /*------------------------------------1.end string結構----------------------------------------------------*/


    /*------------------------------------2.start list結構----------------------------------------------------*/
    /**
     * 增,構建一個列表(先進後去,相似棧)
     * @param String $key KEY名稱
     * @param string $value 值
     * @param $timeOut |num  過時時間
     */
    public function lpush($key, $value, $timeOut = 0)
    {
//          echo "$key - $value \n";
        $re = $this->redisObj[$this->sn]->LPUSH($key, $value);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        return $re;
    }

    /**
     * 增,構建一個列表(先進先去,相似隊列)
     * @param string $key KEY名稱
     * @param string $value 值
     * @param $timeOut |num  過時時間
     */
    public function rpush($key, $value, $timeOut = 0)
    {
//          echo "$key - $value \n";
        $re = $this->redisObj[$this->sn]->RPUSH($key, $value);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        return $re;
    }

    /**
     * 查,獲取全部列表數據(從頭至尾取)
     * @param string $key KEY名稱
     * @param int $head 開始
     * @param int $tail 結束
     */
    public function lranges($key, $head, $tail)
    {
        return $this->redisObj[$this->sn]->lrange($key, $head, $tail);
    }

    /**
     * Power by Mikkle
     * QQ:776329498
     * @param $key
     * @return mixed
     */

    public function rpop($key)
    {
        return $this->redisObj[$this->sn]->rPop($key);
    }

    public function lpop($key)
    {
        return $this->redisObj[$this->sn]->lpop($key);
    }

    /*------------------------------------2.end list結構----------------------------------------------------*/


    /*------------------------------------3.start set結構----------------------------------------------------*/

    /**
     * 增,構建一個集合(無序集合)
     * @param string $key 集合Y名稱
     * @param string|array $value 值
     * @param int $timeOut 時間  0表示無過時時間
     * @return
     */
    public function sadd($key, $value, $timeOut = 0)
    {
        $re = $this->redisObj[$this->sn]->sadd($key, $value);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        return $re;
    }

    /**
     * 查,取集合對應元素
     * @param string $key 集合名字
     */
    public function smembers($key)
    {
        $re = $this->redisObj[$this->sn]->exists($key);//存在返回1,不存在返回0
        if (!$re) return false;
        return $this->redisObj[$this->sn]->smembers($key);
    }

    /*------------------------------------3.end  set結構----------------------------------------------------*/


    /*------------------------------------4.start sort set結構----------------------------------------------------*/
    /*
     * 增,改,構建一個集合(有序集合),支持批量寫入,更新
     * @param string $key 集合名稱
     * @param array $score_value key爲scoll, value爲該權的值
     * @return int 插入操做成功返回插入數量【,更新操做返回0】
     */
    public function zadd($key, $score_value, $timeOut = 0)
    {
        if (!is_array($score_value)) return false;
        $a = 0;//存放插入的數量
        foreach ($score_value as $score => $value) {
            $re = $this->redisObj[$this->sn]->zadd($key, $score, $value);//當修改時,能夠修改,但不返回更新數量
            $re && $a += 1;
            if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        }
        return $a;
    }

    /**
     * 查,有序集合查詢,可升序降序,默認從第一條開始,查詢一條數據
     * @param $key ,查詢的鍵值
     * @param $min ,從第$min條開始
     * @param $max,查詢的條數
     * @param $order ,asc表示升序排序,desc表示降序排序
     * @return array|bool 若是成功,返回查詢信息,若是失敗返回false
     */
    public function zrange($key, $min = 0, $num = 1, $order = 'desc')
    {
        $re = $this->redisObj[$this->sn]->exists($key);//存在返回1,不存在返回0
        if (!$re) return false;//不存在鍵值
        if ('desc' == strtolower($order)) {
            $re = $this->redisObj[$this->sn]->zrevrange($key, $min, $min + $num - 1);
        } else {
            $re = $this->redisObj[$this->sn]->zrange($key, $min, $min + $num - 1);
        }
        if (!$re) return false;//查詢的範圍值爲空
        return $re;
    }

    /**
     * 返回集合key中,成員member的排名
     * @param $key,鍵值
     * @param $member,scroll值
     * @param $type ,是順序查找仍是逆序
     * @return bool,鍵值不存在返回false,存在返回其排名下標
     */
    public function zrank($key, $member, $type = 'desc')
    {
        $type = strtolower(trim($type));
        if ($type == 'desc') {
            $re = $this->redisObj[$this->sn]->zrevrank($key, $member);//其中有序集成員按score值遞減(從大到小)順序排列,返回其排位
        } else {
            $re = $this->redisObj[$this->sn]->zrank($key, $member);//其中有序集成員按score值遞增(從小到大)順序排列,返回其排位
        }
        if (!is_numeric($re)) return false;//不存在鍵值
        return $re;
    }

    /**
     * 返回名稱爲key的zset中score >= star且score <= end的全部元素
     * @param $key
     * @param $member
     * @param $star,
     * @param $end ,
     * @return array
     */
    public function zrangbyscore($key, $star, $end)
    {
        return $this->redisObj[$this->sn]->ZRANGEBYSCORE($key, $star, $end);
    }

    /**
     * 返回名稱爲key的zset中元素member的score
     * @param $key
     * @param $member
     * @return string ,返回查詢的member值
     */
    function zscore($key, $member)
    {
        return $this->redisObj[$this->sn]->ZSCORE($key, $member);
    }
    /*------------------------------------4.end sort set結構----------------------------------------------------*/


    /*------------------------------------5.hash結構----------------------------------------------------*/
    /**
     * 增,以json格式插入數據到緩存,hash類型
     * @param $redis_key |array , $redis_key['key']數據庫的表名稱;$redis_key['field'],下標key
     * @param $token ,該活動的token,用於區分標識
     * @param $id ,該活動的ID,用於區分標識
     * @param $data |array ,要插入的數據,
     * @param $timeOut ,過時時間,默認爲0
     * @return $number 插入成功返回1【,更新操做返回0】
     */
    public function hset_json($redis_key, $token, $id, $data, $timeOut = 0)
    {
        $redis_table_name = $redis_key['key'] . ':' . $token;           //key的名稱
        $redis_key_name = $redis_key['field'] . ':' . $id;              //field的名稱,表示第幾個活動
        $redis_info = json_encode($data);                           //field的數據value,以json的形式存儲
        $re = $this->redisObj[$this->sn]->hSet($redis_table_name, $redis_key_name, $redis_info);//存入緩存
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($redis_table_name, $timeOut);//設置過時時間
        return $re;
    }

    /**
     * 查,json形式存儲的哈希緩存,有值則返回;無值則查詢數據庫並存入緩存
     * @param $redis ,$redis['key'],$redis['field']分別是hash的表名稱和鍵值
     * @param $token ,$token爲公衆號
     * @param $token ,$id爲活動ID
     * @return bool|array, 成功返回要查詢的信息,失敗或不存在返回false
     */
    public function hget_json($redis_key, $token, $id)
    {
        $re = $this->redisObj[$this->sn]->hexists($redis_key['key'] . ':' . $token, $redis_key['field'] . ':' . $id);//返回緩存中該hash類型的field是否存在
        if ($re) {
            $info = $this->redisObj[$this->sn]->hget($redis_key['key'] . ':' . $token, $redis_key['field'] . ':' . $id);
            $info = json_decode($info, true);
        } else {
            $info = false;
        }
        return $info;
    }

    public function hset($redis_key, $name, $data, $timeOut = 0)
    {
        $re = $this->redisObj[$this->sn]->hset($redis_key, $name, $data);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($redis_key, $timeOut);
        return $re;
    }


    /**
     * 增,普通邏輯的插入hash數據類型的值
     * @param $key ,鍵名
     * @param $data |array 一維數組,要存儲的數據
     * @param $timeOut |num  過時時間
     * @return $number 返回OK【更新和插入操做都返回ok】
     */
    public function hmset($key, $data, $timeOut = 0)
    {
        $re = $this->redisObj[$this->sn]->hmset($key, $data);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($key, $timeOut);
        return $re;
    }

    /**
     * 查,普通的獲取值
     * @param $key ,表示該hash的下標值
     * @return array 。成功返回查詢的數組信息,不存在信息返回false
     */
    public function hval($key)
    {
        $re = $this->redisObj[$this->sn]->exists($key);//存在返回1,不存在返回0
        if (!$re) return false;
        $vals = $this->redisObj[$this->sn]->hvals($key);
        $keys = $this->redisObj[$this->sn]->hkeys($key);
        $re = array_combine($keys, $vals);
        foreach ($re as $k => $v) {
            if (!is_null(json_decode($v))) {
                $re[$k] = json_decode($v, true);//true表示把json返回成數組
            }
        }
        return $re;
    }

    /**
     *
     * @param $key
     * @param $filed
     * @return bool|string
     */
    public function hget($key, $filed = [])
    {
        if (empty($filed)) {
            $re = $this->redisObj[$this->sn]->hgetAll($key);
        } elseif (is_string($filed)) {
            $re = $this->redisObj[$this->sn]->hget($key, $filed);
        } elseif (is_array($filed)) {

            $re = $this->redisObj[$this->sn]->hMget($key, $filed);
        }
        if (!$re) {
            return false;
        }
        return $re;
    }

    public function hsetAll($redis_key, $name, $data, $timeOut = 0)
    {
        $re = $this->redisObj[$this->sn]->hset($redis_key, $name, $data);
        if ($timeOut > 0) $this->redisObj[$this->sn]->expire($redis_key, $timeOut);
        return $re;
    }

    public function hdel($redis_key, $name)
    {
        $re = $this->redisObj[$this->sn]->hdel($redis_key, $name);
        return $re;
    }


    /*------------------------------------end hash結構----------------------------------------------------*/


    /*------------------------------------其餘結構----------------------------------------------------*/
    /**
     * 設置自增,自減功能
     * @param $key ,要改變的鍵值
     * @param int $num ,改變的幅度,默認爲1
     * @param string $member ,類型是zset或hash,須要在輸入member或filed字段
     * @param string $type,類型,default爲普通增減 ,還有:zset,hash
     * @return bool|int 成功返回自增後的scroll整數,失敗返回false
     */
    public function incre($key, $num = 1, $member = '', $type = '')
    {
        $num = intval($num);
        switch (strtolower(trim($type))) {
            case "zset":
                $re = $this->redisObj[$this->sn]->zIncrBy($key, $num, $member);//增加權值
                break;
            case "hash":
                $re = $this->redisObj[$this->sn]->hincrby($key, $member, $num);//增加hashmap裏的值
                break;
            default:
                if ($num > 0) {
                    $re = $this->redisObj[$this->sn]->incrby($key, $num);//默認增加
                } else {
                    $re = $this->redisObj[$this->sn]->decrBy($key, -$num);//默認增加
                }
                break;
        }
        if ($re) return $re;
        return false;
    }


    /**
     * 清除緩存
     * @param int $type 默認爲0,清除當前數據庫;1表示清除全部緩存
     */
    function flush($type = 0)
    {
        if ($type) {
            $this->redisObj[$this->sn]->flushAll();//清除全部數據庫
        } else {
            $this->redisObj[$this->sn]->flushdb();//清除當前數據庫
        }
    }

    /**
     * 檢驗某個鍵值是否存在
     * @param $keys ,鍵值
     * @param string $type,類型,默認爲常規
     * @param string $field。若爲hash類型,輸入 $field
     * @return bool
     */
    public function exists($keys, $type = '', $field = '')
    {
        switch (strtolower(trim($type))) {
            case 'hash':
                $re = $this->redisObj[$this->sn]->hexists($keys, $field);//有返回1,無返回0
                break;
            default:
                $re = $this->redisObj[$this->sn]->exists($keys);
                break;
        }
        return $re;
    }

    /**
     * 刪除緩存
     * @param string|array $key,鍵值
     * @param $type,類型,默認爲常規,還有hash ,zset
     * @param string $field ,hash=>表示$field值,set=>表示value,zset=>表示value值,list類型特殊暫時不加
     * @return int | ,返回刪除的個數
     */
    public function delete($key, $type = "default", $field = '')
    {
        switch (strtolower(trim($type))) {
            case 'hash':
                $re = $this->redisObj[$this->sn]->hDel($key, $field);//返回刪除個數
                break;
            case 'set':
                $re = $this->redisObj[$this->sn]->sRem($key, $field);//返回刪除個數
                break;
            case 'zset':
                $re = $this->redisObj[$this->sn]->zDelete($key, $field);//返回刪除個數
                break;
            default:
                $re = $this->redisObj[$this->sn]->del($key);//返回刪除個數
                break;
        }
        return $re;
    }

    //日誌記錄
    public function logger($log_content, $position = 'user')
    {
        $max_size = 1000000;   //聲明日誌的最大尺寸1000K

        $log_dir = './log';//日誌存放根目錄

        if (!file_exists($log_dir)) mkdir($log_dir, 0777);//若是不存在該文件夾,建立

        if ($position == 'user') {
            $log_filename = "{$log_dir}/User_redis_log.txt";  //日誌名稱
        } else {
            $log_filename = "{$log_dir}/Wap_redis_log.txt";  //日誌名稱
        }

        //若是文件存在而且大於了規定的最大尺寸就刪除了
        if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
            unlink($log_filename);
        }

        //寫入日誌,內容前加上時間, 後面加上換行, 以追加的方式寫入
        file_put_contents($log_filename, date('Y-m-d_H:i:s') . " " . $log_content . "\n", FILE_APPEND);
    }


    function __destruct()
    {
        //  $this->redisObj[$this->sn]->close();
    }

    /**
     * 魔術方法 有不存在的操做的時候執行
     * @access public
     * @param string $method 方法名
     * @param array $args 參數
     * @return mixed
     */
    public function __call($method, $args)
    {
        call_user_func_array([$this->redisObj[$this->sn], $method], $args);
    }
相關文章
相關標籤/搜索