安装和配置

安装redis服务和php-redis扩展:https://blog.csdn.net/why444216978/article/details/83659776

主从复制:https://blog.csdn.net/why444216978/article/details/100170179

封装服务类RedisService.php

<?php

class RedisService
{
    private $getObj;
    private $setObj;
    private $name;
    private $config;
    private $host;
    private $port;
    private $auth;
    private $try;
    private $connectTimeout;
    private $db;
    private $readTimeout;

    private $getFunction = array(
        'DUMP',
        'GET',
        'STRLEN',
        'MGET',
        'HKEYS',
        'HGET',
        'HMGET',
        'HGETALL',
        'HVALS',
        'SCAN',
        'SSCAN',
        'ZSCAN',
        'MSSCAN',
        'SMEMBERS',
        'SISMEMBER',
        'SCARD',
        'SPOP',
        'ZRANGEBYSCORE',
        'ZREVRANGEBYSCORE',
        'ZSCORE',
        'ZCOUNT',
        'LRANGE',
        'ZRANGE',
        'ZREVRANGE',
        'ZRANK',
        'ZREVRANK',
        'ZCARD',
        'TTL',
        'LLEN',
        'GETMULTIPLE',
        'EXISTS',
        'HEXISTS',
    );

    private $setFunction = array(
        'PEXPIREAT',
        'EXPIREAT',
        'PEXPIRE',
        'SET',
        'DEL',
        'MSET',
        'DELETE',
        'MSETNX',
        'LREM',
        'LTRIM',
        'INCR',
        'INCRBY',
        'DECR',
        'DECRBY',
        'HSET',
        'HDEL',
        'LPUSH',
        'LMPUSH',
        'RPUSH',
        'RMPUSH',
        'RPOP',
        'HMSET',
        'SADD',
        'SMADD',
        'SREM',
        'SREMOVE',
        'ZADD',
        'ZMADD',
        'ZMREM',
        'ZREM',
        'ZDELETE',
        'ZINCRBY',
        'EXPIRE',
        'HINCRBY',
        'ZREMRANGEBYSCORE',
        'ZREMRANGEBYRANK',
    );

    public function __construct($name = 'default')
    {
        $this->name = $name;
    }

    public function exec($func)
    {
        return $this->getConnectionByFuncName($func);
    }

    private function getConnectionByFuncName($func)
    {
        if (in_array(strtoupper($func), $this->getFunction)) {
            $obj = $this->getReadObj();
        } else if (in_array(strtoupper($func), $this->setFunction)) {
            $obj = $this->getWriteObj();
        }else{
            throw new Exception('function not exists', 10001);
        }

        return $obj;
    }

    private function setConfig()
    {
        $configArr = require_once('./redis_conf.php');
        $this->config = $configArr[$this->name];
        $this->host           = $this->config['host'] ?: '127.0.0.1';
        $this->port           = $this->config['port'] ?: 6379;
        $this->auth           = $this->config['auth'] ?: '';
        $this->try            = $this->config['try'] ?: 5;
        $this->connectTimeout = $this->config['connect_timeout'] ?: 5;
        $this->readTimeout    = $this->config['read_timeout'] ?: 3;
        $this->db             = $this->config['db'] ?: 0;
    }

    private function getReadObj()
    {
        $this->name = $this->name . '_read';
        $this->setConfig();
        if (!isset($this->getObj) || !is_object($this->getObj)) {
            $this->getObj = new Redis();
            for ($i = $this->try; $i > 0; $i--) {
                $re_con = $this->getObj->pconnect($this->host, $this->port, $this->connectTimeout);
                if ($re_con) {
                    break;
                }
            }

            $this->getObj->setOption(Redis::OPT_READ_TIMEOUT, $this->readTimeout);

            $this->auth && $this->getObj->auth($this->auth);
            $this->getObj->select($this->db);
        }
        return $this->getObj;
    }

    private function getWriteObj()
    {
        $this->name = $this->name . '_write';
        $this->setConfig();
        if (!isset($this->conn) || !is_object($this->setObj)) {
            $this->setObj = new Redis();
            for ($i = $this->try; $i > 0; $i--) {
                $re_con = $this->setObj->pconnect($this->host, $this->port, $this->connectTimeout);
                if ($re_con) {
                    break;
                }
            }
            $this->auth && $this->setObj->auth($this->auth);
            $this->setObj->select($this->db);
        }
        return $this->setObj;
    }

    public function __destruct()
    {
    }

}

配置文件redis_conf.php

<?php
return [
    'default_read' => [
        'host' => '127.0.0.1',
        'port' => 7000,
        'auth' => '',
        'try' => 5,
        'connect_timeout' => 5,
        'read_timeout' => 3,
        'db' => 0
    ],
    'default_write' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'auth' => '',
        'try' => 5,
        'connect_timeout' => 5,
        'read_timeout' => 3,
        'db' => 0
    ],
];

单例模式加载库方法

单例模式详解:https://blog.csdn.net/why444216978/article/details/103718450

<?php

function load($class, $config)
{
    static $objs = array();

    $class = strtolower($class);

    if (isset($objs[$class]) && isset($objs[$class][$config])) {
        return $objs[$class][$config];
    }

    if (!isset($objs[$class])) {
        $objs[$class] = [];

        $className = ucfirst($class);
        $objs[$class][$config] = new $className($config);
        return $objs[$class][$config];
    }
}

测试代码

<?php
require_once './RedisService.php';
require_once './helper.php';

$redisObj = load('RedisService', 'default');
$redis = $redisObj->exec('set');
var_dump($redis->set('why', 'why'));
var_dump($redis->get('why'));
/usr/bin/php /Users/why/Desktop/php/why.php
bool(true)
string(3) "why"

Process finished with exit code 0

 

 

 

 

扩展,如果需要记录调用redis的日志,可用下面类,不过需要自己封装每一个用到的方法:

<?php

class Lib_redis
{
    private $_getobj;
    private $_setobj;
    private $_name;
    private $_host;

    private $_getfunction = array(
        'GET',
        'MGET',
        'HKEYS',
        'HGET',
        'HMGET',
        'HGETALL',
        'HVALS',
        'SSCAN',
        'MSSCAN',
        'SMEMBERS',
        'SISMEMBER',
        'SCARD',
        'SPOP',
        'ZRANGEBYSCORE',
        'ZREVRANGEBYSCORE',
        'ZSCORE',
        'ZCOUNT',
        'LRANGE',
        'ZRANGE',
        'ZREVRANGE',
        'ZRANK',
        'ZREVRANK',
        'ZCARD',
        'TTL',
        'LLEN',
        'GETMULTIPLE',
        'EXISTS',
        'HEXISTS',
    );

    private $_setfunction = array(
        'SET',
        'DEL',
        'MSET',
        'LREM',
        'LTRIM',
        'INCR',
        'INCRBY',
        'DECR',
        'DECRBY',
        'HSET',
        'HDEL',
        'LPUSH',
        'LMPUSH',
        'RPUSH',
        'RMPUSH',
        'RPOP',
        'HMSET',
        'SADD',
        'SMADD',
        'SREM',
        'SREMOVE',
        'ZADD',
        'ZMADD',
        'ZMREM',
        'ZREM',
        'ZDELETE',
        'ZINCRBY',
        'EXPIRE',
        'HINCRBY',
        'ZREMRANGEBYSCORE',
        'ZREMRANGEBYRANK',
    );

    public function __construct($name = 'default')
    {
        $this->_conf   = C('redis');
        $this->_name   = $name;
        $this->_logSrv = &load_class('Log', 'core');
    }

    public function getreadobj()
    {
        if (!isset($this->_getobj) || !is_object($this->_getobj)) {
            $server = is_array($this->_conf[$this->_name]) ? $this->_conf[$this->_name] : $this->_conf['default'];

            $this->_host   = $server['host'] . ':' . $server['port'];
            $this->_getobj = new Redis();
            $con           = $this->_getobj->pconnect($server['host'], $server['port'], $server['timeout']);
            if ($con === false && isset($server['retry']) && $server['retry'] > 0) {
                for ($i = $server['retry']; $i > 0; $i--) {
                    $re_con = $this->_getobj->pconnect($server['host'], $server['port'], $server['timeout']);
                    if ($re_con) {
                        break;
                    }
                }
            }

            if (isset($server['read_timeout']) && !empty($server['read_timeout'])) {
                $this->_getobj->setOption(Redis::OPT_READ_TIMEOUT, $server['read_timeout']);
            }
            if (isset($server['auth']) && $server['auth']) {
                $this->_getobj->auth($server['auth']);
            }
            if (isset($server['db'])) {
                $this->_getobj->select($server['db']);
            }else{
                $this->_getobj->select(0);
            }

        }
        return $this->_getobj;
    }

    public function getwriteobj()
    {
        if (!isset($this->_setobj) || !is_object($this->_setobj)) {
            $server = is_array($this->_conf[$this->_name . '_w']) ? $this->_conf[$this->_name . '_w'] : $this->_conf['default_w'];

            $this->_host   = $server['host'] . ':' . $server['port'];
            $this->_setobj = new Redis();
            $con           = $this->_setobj->pconnect($server['host'], $server['port'], $server['timeout']);
            if ($con === false && isset($server['retry']) && $server['retry'] > 0) {
                for ($i = $server['retry']; $i > 0; $i--) {
                    $re_con = $this->_setobj->pconnect($server['host'], $server['port'], $server['timeout']);
                    if ($re_con) {
                        break;
                    }
                }
            }

            if (isset($server['auth']) && $server['auth']) {
                $this->_setobj->auth($server['auth']);
            }
            if (isset($server['db']) && $server['db']) {
                $this->_setobj->select($server['db']);
            }
        }
        return $this->_setobj;
    }

    public function __call($name, $params)
    {
        logStart();
        $return = array('errno' => C('redis.errno.succ'), 'errmsg' => 'SUCCESS');
        try {
            if (in_array(strtoupper($name), $this->_getfunction)) {
                $obj = $this->getreadobj();
            } else if (in_array(strtoupper($name), $this->_setfunction)) {
                $obj = $this->getwriteobj();
            } else {
                $return = array('errno' => 30000, 'errmsg' => 'get params err');
                log($return, $params);
                return $return;
            }
            if (is_string($params)) {
                $res = $obj->$name($params);
            } elseif (method_exists($this, $name)) {
                $res = $this->$name($obj, $params[0]);
            } else {
                $res = $obj->$name($params[0]);
            }
            $return['result'] = $res;
        } catch (Exception $e) {
            $return['errno']  = C('redis.errno.syserr');
            $return['errmsg'] = $e->getMessage();
        }
        log($return, $params, $res, $name);
        return $return;
    }

    private function hget($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['field'])) {
            return false;
        }
        $res = $obj->hget($params['key'], $params['field']);
        return $res;
    }

    private function hexists($obj, $params)
    {
        if (empty($params['key']) || empty($params['field'])) {
            return false;
        }

        $res = $obj->hexists($params['key'], $params['field']);
        return $res;
    }

    private function hset($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value']) || !isset($params['field'])) {
            return false;
        }
        $res = $obj->hset($params['key'], $params['field'], $params['value']);
        return $res;
    }

    private function hdel($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['field'])) {
            return false;
        }
        $res = $obj->hdel($params['key'], $params['field']);
        return $res;
    }

    private function del($obj, $params)
    {
        if (is_array($params)) {
            foreach ($params as $key) {
                $param_arr[] = $key;
            }
            return call_user_func_array([$obj, 'del'], $param_arr);
        } else {
            return $obj->del($params);
        }
    }

    private function set1($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }

        if (isset($params['extra'])) {
            $res = $obj->set($params['key'], $params['value'], $params['extra']);
        }else{
            $res = $obj->set($params['key'], $params['value']);
        }

        return $res;
    }

    private function set($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->set($params['key'], $params['value']);
        if (isset($params['expire'])) {
            $obj->expire(strval($params['key']), intval($params['expire']));
        }

        return $res;
    }

    private function expire($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['expire'])) {
            return false;
        }
        $res = $obj->expire(strval($params['key']), intval($params['expire']));
        return $res;
    }

    private function sadd($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->sadd($params['key'], $params['value']);
        if (isset($params['expire'])) {
            $obj->expire(strval($params['key']), intval($params['expire']));
        }
        return $res;
    }

    private function smadd($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member']) || !is_array($params['member'])) {
            return false;
        }

        $param_arr = array_merge([$params['key']], $params['member']);
        return call_user_func_array([$obj, 'sadd'], $param_arr);
    }

    private function msscan($obj, $params)
    {
        if (!isset($params) || empty($params)) {
            return false;
        }
        $result = [];
        $i      = null;
        while (true) {
            $res = $obj->sscan($params, $i);
            if (!empty($res) && is_array($res)) {
                $result = array_merge($result, $res);
            }
            if (empty($i)) {
                break;
            }
        }
        return $result;
    }

    private function sremove($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->sremove($params['key'], $params['value']);

        return $res;
    }

    private function srem($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->srem($params['key'], $params['value']);

        return $res;
    }

    private function sismember($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->sismember($params['key'], $params['value']);
        return $res;
    }

    private function zrange($obj, $params)
    {
        if (!isset($params['key'])) {
            return false;
        }
        if (isset($params['withscores']) && $params['withscores'] === true) {
            $res = $obj->zrange($params['key'], $params['start'], $params['end'], true);
        } else {
            $res = $obj->zrange($params['key'], $params['start'], $params['end']);
        }

        return $res;
    }

    private function zrevrange($obj, $params)
    {

        if (!isset($params['key']) || !isset($params['start']) || !isset($params['end'])) {
            return false;
        }
        if (isset($params['other']) && true === $params['other']) {
            $res = $obj->zrevrange($params['key'], $params['start'], $params['end'], $params['other']);
        } else {
            $res = $obj->zrevrange($params['key'], $params['start'], $params['end']);
        }
        return $res;
    }

    private function zrangebyscore($obj, $params)
    {
        if (!isset($params['key'])) {
            return false;
        }

        $res = $obj->zrangebyscore($params['key'], $params['star'], $params['end'], $params['other']);
        return $res;
    }

    private function zrevrangebyscore($obj, $params)
    {
        if (!isset($params['key'])) {
            return false;
        }

        $res = $obj->zrevrangebyscore($params['key'], $params['start'], $params['end'], $params['other']);
        return $res;
    }

    private function zremrangebyscore($obj, $params)
    {
        if (!isset($params['key'])) {
            return false;
        }

        $res = $obj->zremrangebyscore($params['key'], $params['star'], $params['end']);
        return $res;
    }

    private function zrank($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zrank($params['key'], $params['member']);

        return $res;
    }

    private function zrevrank($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zrevrank($params['key'], $params['member']);

        return $res;
    }

    private function zrem($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zrem($params['key'], $params['member']);
        return $res;
    }

    private function zadd($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zadd($params['key'], $params['score'], $params['member']);
        if (isset($params['expire'])) {
            $obj->expire($params['key'], $params['expire']);
        }
        return $res;
    }

    private function zmadd($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member']) || !is_array($params['member']) || !is_array($params['score'])) {
            return false;
        }
        $cs = count($params['score']);
        $cm = count($params['member']);

        if ($cm !== $cs) {
            return false;
        }

        $param_arr = [$params['key']];
        for ($i = 0; $i < $cm; $i++) {
            $param_arr[] = $params['score'][$i];
            $param_arr[] = $params['member'][$i];
        }
        return call_user_func_array([$obj, 'zadd'], $param_arr);
    }

    private function zmrem($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member']) || !is_array($params['member'])) {
            return false;
        }
        $cm = count($params['member']);

        $param_arr = [$params['key']];
        for ($i = 0; $i < $cm; $i++) {
            $param_arr[] = $params['member'][$i];
        }
        return call_user_func_array([$obj, 'zrem'], $param_arr);
    }

    private function zscore($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zscore($params['key'], $params['member']);
        return $res;
    }

    private function zdelete($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zdelete($params['key'], $params['member']);
        return $res;
    }

    private function zcard($obj, $params)
    {
        if (empty($params)) {
            return false;
        }
        $res = $obj->zcard($params);
        return $res;
    }

    private function zcount($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['star']) || !isset($params['end'])) {
            return false;
        }
        $res = $obj->zcount($params['key'], $params['star'], $params['end']);
        return $res;
    }

    private function zremrangebyrank($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['start']) || !isset($params['end'])) {
            return false;
        }
        $res = $obj->zremrangebyrank($params['key'], $params['start'], $params['end']);
        return $res;
    }

    private function ltrim($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['start']) || !isset($params['end'])) {
            return false;
        }
        $res = $obj->ltrim($params['key'], $params['start'], $params['end']);
        return $res;
    }

    private function lrem($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['num']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->lrem($params['key'], $params['member'], $params['num']);
        return $res;
    }
    private function incrby($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->incrby($params['key'], $params['value']);
        return $res;
    }
    
    private function decrby($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->decrby($params['key'], $params['value']);
        return $res;
    }
  
    private function zincrby($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['increment']) || !isset($params['member'])) {
            return false;
        }
        $res = $obj->zincrby($params['key'], $params['increment'], $params['member']);
        if (isset($params['expire'])) {
            $obj->expire($params['key'], $params['expire']);
        }
        return $res;
    }

    private function rpush($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['data'])) {
            return false;
        }
        $res = $obj->rpush($params['key'], $params['data']);
        return $res;
    }

    private function rmpush($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['data']) || !is_array($params['data'])) {
            return false;
        }

        $param_arr = [$params['key']];
        foreach ($params['data'] as $value) {
            $param_arr[] = $value;
        }
        return call_user_func_array([$obj, 'rpush'], $param_arr);
    }

    private function lpush($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['data'])) {
            return false;
        }
        $res = $obj->lpush($params['key'], $params['data']);
        return $res;
    }
  
    private function lmpush($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['data']) || !is_array($params['data'])) {
            return false;
        }

        $param_arr = [$params['key']];
        foreach ($params['data'] as $value) {
            $param_arr[] = $value;
        }
        return call_user_func_array([$obj, 'lpush'], $param_arr);
    }

    private function lrange($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['start']) || !isset($params['end'])) {
            return false;
        }
        $res = $obj->lrange($params['key'], $params['start'], $params['end']);
        return $res;
    }

    private function hmget($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['fields']) || !is_array($params['fields'])) {
            return false;
        }
        $res = $obj->hmget($params['key'], $params['fields']);
        return $res;
    }
  
    private function hmset($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value'])) {
            return false;
        }
        $res = $obj->hmset($params['key'], $params['value']);
        if (isset($params['expire'])) {
            $obj->expire(strval($params['key']), intval($params['expire']));
        }
        return $res;
    }

    private function hincrby($obj, $params)
    {
        if (!isset($params['key']) || !isset($params['value']) || !isset($params['field'])) {
            return false;
        }
        $res = $obj->hIncrBy($params['key'], $params['field'], $params['value']);
        return $res;
    }

    public function multi($model = "PIPELINE", $readonly = true)
    {
        $obj = $this->getreadobj();
        if (!$readonly) {
            $obj = $this->getwriteobj();
        }
        $model = $model == "PIPELINE" ? (Redis::PIPELINE) : (Redis::MULTI);
        $obj->multi($model);
        return $obj;
    }

    public function exec($obj)
    {
        $return = array('errno' => C('redis.errno.succ'), 'errmsg' => 'SUCCESS');
        try {
            $return['result'] = $obj->exec();
        } catch (Exception $e) {
            $return['errno']  = C('redis.errno.syserr');
            $return['errmsg'] = $e->getMessage();
        }

        return $return;
    }

    public function __destruct()
    {
        // if (is_object($this->_getobj) && method_exists($this->_getobj, 'close')) {
        //     $this->_getobj->close();
        // }
        // if (is_object($this->_setobj) && method_exists($this->_setobj, 'close')) {
        //     $this->_setobj->close();
        // }
    }

}

 

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐