设为首页 收藏本站
查看: 1747|回复: 0

[经验分享] redis操作封装类

[复制链接]

尚未签到

发表于 2017-12-21 11:05:50 | 显示全部楼层 |阅读模式
redis操作封装类
class Redis {    // 默认配置名称(使用load_config加载)private $_default_config_path = 'package/cache/redis';    // redis实例对象    private $_redis;    // redis服务器地址    private $_host = '';    // redis服务器端口    private $_port = 6379;        /**      * 构造函数     *      * @access public     * @param array $conf 配置文件集合, 包含参数:     *              string $host 服务器地址     *              string $port 服务器端口     * @return void     */    public function __construct(array $conf=array()) {        $this -> set_conf($conf);        $this -> reconnect(true);    }    /**     * 设置redis配置     * 执行前,配置会被重置为[host='', port='6379']     *     * @access public     * @param array $conf 配置文件集合, 包含参数:     *              string $host 服务器地址     *              string $port 服务器端口     * @return void     */    public function set_conf(array $conf=array()) {        if (empty($conf)) {            $conf = load_config($this -> _default_config_path);            if (!is_array($conf) or empty($conf)) {                to_log(MAIN_LOG_ERROR, '', __CLASS__ . ':' . __FUNCTION__ . ': 默认配置为空');                return;            }        }        $this -> _host = '';        $this -> _port = 6379;        isset($conf['host']) and $this -> _host = $conf['host'];        isset($conf['port']) and $this -> _port = intval($conf['port']);    }        /**      * 重新连接redis     *      * @access public     * @param boolean $is_new 是否必须重新连接     * @return boolean     */    public function reconnect($is_new=false) {        $ret = false;        if ($is_new) {            $ret = $this -> _connect();            return $ret;        }        $check = $this -> _is_connected();        if (!$check) {            $ret = $this -> _connect();        }        return $ret;    }        /**      * 设置缓存数据, 仅支持字符串     *      * @access public     * @param string $key 缓存变量名     * @param string $value 缓存变量值     * @param string $ttl 缓存生存时间,单位:秒     * @return boolean     */    public function set($key, $value, $ttl=3600) {        $key = strval($key);        $value = strval($value);        $ttl = intval($ttl);        $ttl < 0 and $ttl = 0;        if ($key === '' or $value === '') {            return false;        }                try {            $result = $this -> _redis -> setex($key, $ttl, $value);        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }    /**      * 重新设置缓存变量的生存时间     *      * @access public     * @param string $key 缓存变量名     * @param string $ttl 缓存生存时间,单位:秒     * @return boolean     */    public function expire($key, $ttl=3600) {        $key = strval($key);        $ttl = intval($ttl);        $ttl < 0 and $ttl = 0;        if ($key === '') {            return false;        }                try {            $result = $this -> _redis -> expire($key, $ttl);        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }    /**      * 获取缓存变量值     *      * @access public     * @param string $key 缓存变量名     * @return mixed 成功返回变量值,失败返回false     */    public function get($key) {        $key = strval($key);        if ($key === '') {            return false;        }        try {            $result = $this -> _redis -> get($key);        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result;    }        /**      * 批量删除缓存变量     *      * @access public     * @param mixed $key [string|array] 当为string时,自动转换为array     * @return boolean     */    public function delete($key) {        !is_array($key) and $key = array($key);        $tmp_arr = array();        foreach ($key as $val) {            $tmp_str = strval($val);            $tmp_str !== '' and $tmp_arr[$tmp_str] = 1;        }        $key = array_keys($tmp_arr);        try {            $ret = true;            foreach ($key as $val) {                $result = $this -> _redis -> delete($val);                !$result and $ret = false;            }        }catch(\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }                return  $ret;    }        /**      * 清空redis中的所有数据     *      * @access public     * @return boolean     */    public function clear() {        try {            $result = $this -> _redis -> flushAll();        }catch(\RedisException $e){            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }        /**      * 将缓存变量放入redis队列,仅支持字符串及整型     *      * @access public     * @param string $key 缓存变量名     * @param string $value 缓存变量值     * @param boolean $to_right 是否从右边入列     * @return boolean     */    public function push($key, $value, $to_right=true) {        $key = strval($key);        $value = strval($value);                if ($key === '' or $value === '') {            return false;        }                $func = 'rPush';        !$to_right and $func = 'lPush';        try {            $result = $this -> _redis -> $func($key, $value);        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }    /**      * 缓存变量出列     *      * @access public     * @param string $key 缓存变量名     * @param boolean $from_left 是否从左边出列     * @return boolean 成功返回缓存变量值,失败返回false     */    public function pop($key , $from_left=true) {        $key = strval($key);        if ($key === '') {            return false;        }        $func = 'lPop';        !$from_left and $func = 'rPop';                try {            $result = $this -> _redis -> $func($key);        }catch(\RedisException $e){            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result;    }        /**      * 缓存变量自增     *      * @access public     * @param string $key 缓存变量名     * @return boolean     */    public function increase($key) {        $key = strval($key);        if ($key === '') {            return false;        }        try {            $result = $this -> _redis -> incr($key);        }catch(\RedisException $e){            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }    /**      * 缓存变量自减     *      * @access public     * @param string $key 缓存变量名     * @return boolean 成功返回TRUE,失败返回FALSE     */    public function decrease($key) {        $key = strval($key);        if ($key === '') {            return false;        }        try {            $result = $this -> _redis -> decr($key);        }catch(\RedisException $e){            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }        /**      * 判断缓存变量是否已经存在     *      * @access public     * @param string $key 缓存变量名     * @return boolean 存在返回TRUE,否则返回FALSE     */    public function exists($key) {        $key = strval($key);        if ($key === '') {            return false;        }        try {            $result = $this -> _redis -> exists($key);        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return $result ? true : false;    }        /**      * 返回redis源对象     *      * @access public     * @return object     */    public function get_handler() {        return $this -> _redis;    }    // ---------私有实现---------------------------------------------    /**     * 检验并连接redis服务器     *     * @access private     * @return boolean     */    private function _connect() {        if (!class_exists('\Redis', false)) {            to_log(MAIN_LOG_ERROR, '', 'Redis类不存在,可能是没有安装php_redis扩展');            return false;        }        try {            $this -> _redis = new \Redis();            $this -> _redis -> connect($this -> _host, $this -> _port);        }catch(\RedisException $e){            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return true;    }    /**      * 判断是否已连接到服务器     *      * @access public     * @return boolean     */     public function _is_connected() {        if(!is_object($this -> _redis)) return false;        try {            $this -> _redis -> ping();        }catch (\RedisException $e) {            to_log(MAIN_LOG_WARN, '', __CLASS__ . " -> " . __FUNCTION__ . ": " . $e -> getMessage());            return false;        }        return true;    }}  posted on 2017-05-06 13:30 官朝辉 阅读(...) 评论(...)  编辑 收藏

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-426390-1-1.html 上篇帖子: 使用python来搞定redis的订阅功能 下篇帖子: ASP.NET Core 使用Redis存储Session
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表