kopug memo

名古屋で働くとあるWebエンジニアの覚書。

memcachedを使ってみるの!!

■ インストール編
ミジンコは素直にyumです。

# yum install php-pecl-memcache

これでmemcached本体も入ります。
memcachedを起動

$ memcached -d -m 128 -p 11211

128M確保で11211ポートで待ちうけ

PHPのサンプル

<?php

 $memcache = new Memcache;
 $memcache->connect('localhost', 11211) or die ("Could not connect");

 if ($memcache) {
    $memcache->set("str_key", "文字列を格納");
    $memcache->set("num_key", 123); // 数値を格納

    $object = new StdClass;
    $object->attribute = 'test';
    $memcache->set("obj_key", $object); // オブジェクトを格納

    $array = Array('assoc'=>123, 345, 567);
    $memcache->set("arr_key", $array);  // 配列を格納

        echo ( print_r($memcache->get('str_key'), true ))."\n";
        echo ( print_r($memcache->get('num_key'), true ))."\n";
        echo ( print_r($memcache->get('obj_key'), true ))."\n";
        echo ( print_r($memcache->get('arr_key'), true ))."\n";
 }
 else {
    echo "Connection to memcached failed";
 }
?>

実行結果

文字列を格納
123
stdClass Object
(
    [attribute] => test
)

Array
(
    [assoc] => 123
    [0] => 345
    [1] => 567
)

サンプルはこんな感じで簡単に動いた。
これでオブジェクトの永続化もできるわけか。