您的位置:首页 > 编程语言 > PHP开发

打造先进的内存KV数据库-6 PHP支持

2016-01-05 23:50 676 查看

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传输也占用了大量时间,考虑之后进行改进,可以支持批量数据处理,不过单线程速度已经是一流的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: