PHP
php作爲使用極廣的程序設計語言,monkey數據庫對php的支持是必須的~
代碼實現
//test.php
<?php
class MonkeyDB
{
private $socket;
private function read()
{
$data = "";
$total = 0;
$t = fread($this->socket,1024);
for($i = 0;$i < 4;$i++)
{
$total *= 256;
$total += ord($t[$i]);
}
$data = substr($t,4);
$total -= 1024;
while($total > 0)
{
$buf = fgets($this->socket,1024);
$data .= $buf;
$total -= 1024;
}
return $data;
}
private function write($string)
{
$total = strlen($string) + 4;
fwrite($this->socket,strrev(pack("L",$total)).$string);
}
public function __construct($addr)
{
set_time_limit(0);
ob_implicit_flush();
$this->socket = stream_socket_client("tcp://{$addr}:1517");
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
}
public function __destruct()
{
fclose($this->socket);
}
//data: string serialize if necessary
public function set($key,$data)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("set {$key} ".($data));
$this->read();
}
//return: string
public function get($key)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("get {$key}");
$data = $this->read();
return ($data);
}
public function remove($key)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("remove {$key}");
$this->read();
}
public function createDB($dbName)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("createdb {$dbName}");
$this->read();
}
public function switchDB($dbName)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("switchdb {$dbName}");
$data = $this->read();
}
public function dropDB($dbName)
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("dropdb {$dbName}");
}
//return string
public function listDB()
{
if(!$this->socket)
{
throw new Exception("monkey 連接失敗!");
}
$this->write("listdb ");
$data = $this->read();
return $data;
}
}
$monkey = new MonkeyDB("127.0.0.1");
for($i = 0;$i < 100000;$i++)
$monkey->set("{$i}","{$i}");
經測試使用php調用,在我的256K緩存CPU,8G筆記本內存可以達到15000req/s每個請求1K數據左右的速度,TCP傳輸也佔用了大量時間,考慮之後進行改進,可以支持批量數據處理,不過單線程速度已經是一流的。