Redis客户端


Redis客户端

根据redis协议写的php连接redis服务的客户端程序,目前只实现了简单的set和get功能。



<?php

class redis{

    protected $con;
    public $host;
    public $port;

    function __construct($config = '', $auto = 0){
        $this->host = $config['redis']['host'];
            $this->port = $config['redis']['port'];
        if($auto == 1){
            // 自动连接
            $socket = $this->connect();
            return $socket;
        }
    }

    function connect(){
        if(!empty($this->con)){
            fclose($this->con);
            $this->con = null;
        }
        // 发起连接
        $socket = fsockopen($this->host, $this->port, $errno, $errstr);
        if(!$socket){
            $this->error('Connection error: '.$errno.':'.$errstr);
            return false;
        }
        $this->con = $socket;
        return $socket;
    }

    function send($args){
        $command = '*'.count($args)."rn";
        foreach($args as $arg){
            $command .= '$'.strlen($arg)."rn".$arg."rn";
        }
        $w = fwrite($this->con, $command);
        if($w){
            $reply = $this->reply();
            return $reply;
        }else{
            return false;
        }

    }

    function reply(){
        $reply = fgets($this->con);
        if($reply == false){
            return false;
        }
        $reply = trim($reply);
        $result = null;
        switch ($reply[0]){
            case '-':
                $this->error('error: '.$reply);
                return false;
            case '+':
                return substr($reply, 1);
            case '$':
                if ($reply=='$-1'){
                    return null;
                }
                $size = intval(substr($reply, 1));
                if($size > 0){
                    $result = stream_get_contents($this->con, $size);
                }
                fread($this->con, 2);
                break;
            case '*':
                break;
            case ':':
                return intval(substr($reply, 1));
            default:
                $this->error('Non-protocol answer: '.print_r($reply, 1));
                return false;
        }
        return $result;
    }

    function set(){
        $args = func_get_args();
        array_unshift($args, 'set');
        return $this->send($args);
    }

    function get(){
        $args = func_get_args();
        array_unshift($args, 'get');
        return $this->send($args);
    }

    protected function error($msg){
        trigger_error($msg, E_USER_WARNING);
    }

    function __destroy(){
        if(!empty($this->con)){
            fclose($this->con);
        }
    }

}

$config = array('redis'=>array('host'=>'localhost', 'port'=>'6379'));

$con = new redis($config, 1);

// $reply = $con->set('name', 'mogu1');

$reply = $con->get('name');

var_dump($reply);


发表回复