您的位置:首页 > 数据库 > Redis

RedisCache

2013-11-16 16:20 316 查看
<?php

/**
 * @author chenliujin <liujin.chen@qq.com>
 * @since 2013-11-16
 */
class RedisCache
{
    public static $host;
    public static $port;
    public static $db;

    protected static $redis;

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function getInstance()
    {
        try {
            if (empty(self::$redis)) {
                $host = !empty(self::$host) ? self::$host : (defined('REDIS_HOST') ? REDIS_HOST : '127.0.0.1');
                $port = !empty(self::$port) ? self::$port : (defined('REDIS_PORT') ? REDIS_PORT : 6379);
                $db   = !empty(self::$db)   ? self::$db   : (defined('REDIS_DB')   ? REDIS_DB   : '');

                self::$redis = new Redis();
                self::$redis->connect($host, $port);

                if ($db) self::$redis->select($db);
            }

            return self::$redis;
        } catch (Exception $e) {
            error_log('FILE: ' . __FILE__);
            error_log('LINE: ' . __LINE__);
            error_log('ERROR: ' . var_export($e, TRUE));

            return FALSE;
        }
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function set($key, $value, $timeout=0)
    {
        self::getInstance();

        self::$redis->set($key, json_encode($value, TRUE));

        if ($timeout > 0) {
            self::$redis->setTimeout($key, $timeout);
        }
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function get($key)
    {
        self::getInstance();

        $ret = self::$redis->get($key);

        return json_decode($ret, TRUE);
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function exists($key)
    {
        try {
            self::getInstance();

            return self::$redis->exists($key);
        } catch (Exception $e) {
            return FALSE;
        }
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function incr($key)
    {
        self::getInstance();

        return self::$redis->incr($key);
    }

    /**
     * @author LJ <liujin.chen@qq.com>
     * @since 2014-02-25
     */
    public static function keys($key)
    {
        self::getInstance();

        return self::$redis->keys($key);
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-20
     */
    public static function flushDB()
    {
        self::getInstance();

        return self::$redis->flushDB();
    }

    /**
     * @author chenliujin <liujin.chen@qq.com>
     * @since 2013-11-16
     */
    public static function flushAll()
    {
        self::getInstance();

        return self::$redis->flushAll();
    }
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: