2016-10-04 96 views
0

我目前正在學習memcache。做一些簡單的get/set查詢,發現一個奇怪的行爲。php memcache返回END時,它不應該

這就是我如何設置和獲取查詢。

$memClient = new MemcacheClient('localhost', 11211); 
$memClient->set('get1', 'value of get1'); 
$memClient->set('get2', 'value of get2'); 
$memClient->get('get1'); 
$memClient->get('get2'); 

這就是我的簡單MemcacheClient

Class MemcacheClient 
{ 
    private $socket; 

    private $reply; 

    private $replies = [ 
     'OK' => true, 
     'EXISTS' => false, 
     'DELETED' => true, 
     'STORED' => true, 
     'NOT_STORED' => false, 
     'NOT_FOUND' => false, 
     'ERROR' => null, 
     'CLIENT_ERROR' => null, 
     'SERVER_ERROR' => null 
    ]; 

    public function __construct($host, $port) 
    { 
     $this->socket = stream_socket_client("$host:$port", $errno, $errstr); 

     if(!$this->socket) { 
      throw new \Exception("$errst ($errno)"); 
     } 
    } 

    public function get($key) 
    { 
     $reply = $this->query("get $key"); 

     return $reply; 
    } 

    public function set($key, $value, $exptime = 0, $flags = 0) 
    { 
     return $this->query(array("set $key $flags $exptime ".strlen($value), $value)); 
    } 

    private function query($query) 
    { 
     $query = is_array($query) ? implode("\r\n", $query) : $query; 
     fwrite($this->socket, $query."\r\n"); 

     return $this->parseLine(); 
    } 

    private function parseLine() 
    { 
     $line = fgets($this->socket); 
     print $line.'<br>'; 
     $this->reply = substr($line, 0, strlen($line) - 2); 

     $words = explode(' ', $this->reply); 

     $result = isset($this->replies[$words[0]]) ? $this->replies[$words[0]] : $words; 

     if (is_null($result)) { 
      throw new \Exception($this->reply); 
     } 

     if ($result[0] == 'VALUE') { 
      $value = fread($this->socket, $result[3] + 2); 

      return $value; 
     } 

     return $result; 
    } 
} 

的 'GET1' 鍵首先獲得查詢響應VALUE GET1的 'get2' 鍵0 13 第二個GET查詢效應初探是END

如果我做兩次,第三個響應將返回值,第四個將再次返回END。

任何想法爲什麼?

感謝

回答

0

看起來根據memcached protocol,檢索請求命令還沒有完成,直到收到END,但我沒有看到你的代碼佔了這一點。

我覺得你的代碼,你需要保持在一個getgets命令END直至接收到呼叫fgets(),然後解析結果。

相關問題