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;
    }
}

redis操作封装类的更多相关文章

  1. Atitit.redis操作总结

    Atitit.redis操作总结 1.1. 获取redis所有kv1 1.2. dbsize:返回当前数据库中key的数目 1 1.3. 一起吧所有key列出来1 1.4. Java连接redis   ...

  2. 基于 php-redis 的redis操作

    基于 php-redis 的redis操作 林涛 发表于:2016-5-13 12:12 分类:PHP 标签:php,php-redis,redis 203次 redis的操作很多的,下面的例子都是基 ...

  3. redis操作

    测试环境redis操作 cd /export/servers/redis-2.8.9/src/./redis-cli -n 0 keys keys(pattern):返回满足给定pattern的所有k ...

  4. php的redis 操作类,适用于单台或多台、多组redis服务器操作

    redis 操作类,包括单台或多台.多组redis服务器操作,适用于业务复杂.高性能要求的 php web 应用. redis.php: <?php /* redis 操作类,适用于单台或多台. ...

  5. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  6. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  7. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  8. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  9. 设计模式之PHP项目应用——单例模式设计Memcache和Redis操作类

    1 单例模式简单介绍 单例模式是一种经常使用的软件设计模式. 在它的核心结构中仅仅包括一个被称为单例类的特殊类. 通过单例模式能够保证系统中一个类仅仅有一个实例并且该实例易于外界訪问.从而方便对实例个 ...

随机推荐

  1. 开源流媒体服务器SRS学习笔记(2) - rtmp / http-flv / hls 协议配置 及跨域问题

    对rtmp/http-flv/hls这三种协议不熟悉的同学,强烈建议先看看网友写的这篇文章科普下:理解RTMP.HttpFlv和HLS的正确姿势 .   srs可以同时支持这3种协议,只要修改conf ...

  2. ASP.NET Core托管和部署Linux实操演练手册

    一.课程介绍 ASP.NET Core 是一种全新的跨平台开源 .NET 框架,能够在 IIS.Nginx.Apache.Docker 上进行托管或在自己的进程中进行自托管. 作为一个.NET Web ...

  3. Creating a NuGet Package in 7 easy steps - Plus using NuGet to integrate ASP.NET MVC 3 into existing Web Forms applications

    UPDATE: Check out my follow up post where I remove the need for editing the Global.asax.cs and show ...

  4. git stash命令详解

    git stash命令用于将更改储藏在脏工作目录中. 使用语法 git stash list [<options>] git stash show [<stash>] git ...

  5. 跟着柴毛毛学Spring(3)——简化Bean的配置

    通过前面的学习.我们会感觉到对于一个有较多Bean的大项目,Spring的配置会比較复杂. 那么接下来我们就介绍怎样简化Spring的配置. 简化Spring的配置主要分为两类: 1. 自己主动装配 ...

  6. BFC 形成条件

    块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域. 下列方式会创建块格 ...

  7. MATLAB 程序计算结果出现 复数(a+bi)问题

    存在对负数开根号的情况了: >> (0.777)^0.1 ans = 0.9751 >> ( ans = 0.6037 >> (0.777)^2.1 ans = 0 ...

  8. int转换char的正确姿势

    一:背景 在一个项目中,我需要修改一个全部由数字(0~9)组成的字符串的特定位置的特定数字,我采用的方式是先将字符串转换成字符数组,然后利用数组的位置来修改对应位置的值.代码开发完成之后,发现有乱码出 ...

  9. Elasticsearch索引mapping的写入、查看与修改(转)

    mapping的写入与查看 首先创建一个索引: curl -XPOST "http://127.0.0.1:9200/productindex" {"acknowledg ...

  10. 从零开始unity特效(持续追加中)

    打算重拾3d渲染了,计划把主要理论过一遍,每部分琢磨一个言之有物的demo. 因为很多东西要现学,再加上上班-8h,更新会比较慢,但会坚持. (待续) -------houdini+unity河流(2 ...