<?php
    include_once ('s/RedisCounter.class.php');        
    $oRedisCounter = new RedisCounter();     
    // 定义保存计数的健值
    $key = 'mycounter';     
    // 执行自增计数,获取当前计数,重置计数
    //echo $oRedisCounter->incr($key).PHP_EOL; // 1
    //echo $oRedisCounter->get($key).PHP_EOL; // 0 
   ?>    
<?php
class RedisCounter
{
    private $_config;
    private $redis = null;

    public function flush()
    {
        return $this->redis->flushDb();
    }
 
    /**
     * 初始化
     * @param Array $config redis连接设定
     */
    public function __construct(){ 
        $this->_config =array(
                            'host' => 'localhost',
                            'port' => 6379,
                            'index' => 0,
                            'auth' => '',
                            'timeout' => 1,
                            'reserved' => NULL,
                            'retry_interval' => 100,
                        );;
        $this->_redis = $this->connect();
    }
 
    /**
     * 执行自增计数并获取自增后的数值
     * @param  String $key  保存计数的键值
     * @param  Int    $incr 自增数量,默认为1
     * @return Int
     */
    public function incr($key, $incr=1){
        return intval($this->_redis->incr($key, $incr));
    }
 
    /**
     * 获取当前计数
     * @param  String $key 保存计数的健值
     * @return Int
     */
    public function get($key){
        return intval($this->_redis->get($key));
    }
 
    /**
     * 重置计数
     * @param  String  $key 保存计数的健值
     * @return Int
     */
    public function reset($key){
        return $this->_redis->delete($key);
    }
 
    /**
     * 创建redis连接
     * @return Link
     */
    private function connect(){
        try{
            $redis = new Redis();
            $redis->connect($this->_config['host'],$this->_config['port'],$this->_config['timeout'],$this->_config['reserved'],$this->_config['retry_interval']);
            /*
            if(empty($this->_config['auth'])){
                $redis->auth($this->_config['auth']);
            }
            */
            $redis->select($this->_config['index']);
        }catch(RedisException $e){
            throw new Exception($e->getMessage());
            return false;
        }
        return $redis;
    }

    
}
?>