kyototycoon PHPから利用する
[http://fallabs.com/blog-ja/promenade.cgi?id=99]
複雑なことはしないので、簡単に書いてみる。set get play_script outくらい
protected $host = ‘localhost';
protected $port = ‘50311’;
protected $timeout = 3;
protected $baseUrl = ”;
protected $kt ;
public function __construct(){
$this->setBase();
}
protected function setBase(){
$this->baseUrl = ‘http://’.$this->host.':’.$this->port.’/rpc/';
}
public function get($key,$db=null){
$api = $this->baseUrl.’get';
$params = array(‘key’=>$key );
if($db) $params['DB']=$db;
return $this->post($api, $params);
}
public function set($key, $value, $db=null){
$api = $this->baseUrl.’set';
$params = array(‘key’=>$key, ‘value’=>$value );
if($db) $params['DB']=$db;
return $this->post($api, $params);
}
protected function ary2tsv( $params ){
$tsv = “”;
foreach($params as $key=>$value){
$tsv .= $key.”\t”.rawurlencode($value).”\n”;
}
return $tsv;
}
protected function tsv2ary( $response ){
if($response){
$data = array();
$list = explode(“\n”,$response);
foreach($list as $item){
$kv = explode(“\t”, $item);
if(count($kv)==2){
$data[$kv[0]]=rawurldecode($kv[1]);
}
}
return $data;
}
return false;
}
protected function post($api, $data){
$ch = curl_init($api);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(“Content-Type: text/tab-separated-values; colenc=U”));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->ary2tsv($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$response = curl_exec($ch);
curl_close($ch);
if($response){
return $this->tsv2ary( $response );
}
return false;
}
}
特に注意する部分はないですが
・tsvに変換
・urlencodeして、http ヘッダーを追加する。 Uの
testしてみる。
$response = $db->set(‘nasdaq’, serialize( array(“ドラゴン”=>1999)),0 );
$response = $db->get(‘nasdaq’, 0);
var_dump($response);
実行すると
["value"]=>
string(33) “a:1:{s:12:”ドラゴン”;i:1999;}”
}
良い感じになりました。
dbを複数扱かう場合。起動時に設定した順に 0 からだそうです。
間違えたdb番号の場合。
["ERROR"]=>
string(16) “no such database”
}
データが無い場合
["ERROR"]=>
string(27) “DB: 7: no record: no record”
}
この辺の処理もクラスに入れてしまって良さそうですね。
ここまでの導入の容易さはオススメです。
各言語のフレームワークもみなさん書かれているので、そちらを利用した方が良いかと思います。
次は、1000万くらいのデータを入れてみて本番に置き換えたいと思います。