Memcached为具有大量选择的小型数据库带来好处

时间:2010-11-21 15:17:47

标签: php mysql memcached

我正在使用mysql作为数据库在php中构建一个Web应用程序。

我正在使用memcached来存储会话,我在想是否也应该存储(在另一个memcached实例中)数据库记录。

db会很小并且偶尔更新一次。不过会有很多选择,因为我们期待高流量。

对于一个小型数据库,如果我将记录存储在memcached中,或者我应该将它留给mysql缓存并调整数据库以获取大量连接(希望优化mysql的一些指针),我会受益吗?

由于

1 个答案:

答案 0 :(得分:0)

为什么不运行一些基准测试然后传播负载!!

http://www.php.net/manual/en/intro.apc.php

Page generated in 0.003202 secs using 2 DB calls and 0 DBCache hits (users ttl=5 countries ttl=5 and both items have expired)

Page generated in 0.002728 secs using 1 DB calls and 1 DBCache hits (users ttl=5 countries ttl=immortal and users has expired)

Page generated in 0.000067 secs using 0 DB calls and 2 DBCache hits (users ttl=5 countries ttl=immortal and both are fetched from cache)

how fast - 0.000067 ouch !! 

使用APC示例PHP脚本

<?php

require_once "CacheDB.php";

ob_start(); 

echo "<h3>APC info:</h3>";

print_r(apc_sma_info());

try{

    //I assume you've already have a db connection available for the cacheDB to use

    $db = @new mysqli("127.0.0.1","foo_dbo","pass","foo_db",3306);

    if ($db->connect_errno)
        throw new Exception("Could not connect: " . $db->connect_error);

    //start the demo...

    $startTime = microtime(true);

    $cacheDB = new CacheDB($db);

    $rows = $cacheDB->Query("call list_users()", CacheDB::TTL_5); //5 second Time To Live (TTL) (30 secs might be more realistic)
    if($rows){
        echo "<h3>Users:</h3><ul>";
        foreach($rows as $row) echo sprintf("<li>%s</li>", $row["username"]);
        echo "</ul>";
    }

    $rows = $cacheDB->Query("call list_countries()", CacheDB::TTL_IMMORTAL); //never expires

    if($rows){
        echo "<h3>Countries:</h3><ul>";
        foreach($rows as $row) echo sprintf("<li>%s</li>", $row["name"]);
        echo "</ul>";
    }

    echo sprintf("<p><b>Page generated in %s secs using %d DB calls and %d DBCache hits</b></p><p>Refresh me !!</p>",
            number_format(microtime(true) - $startTime, 6, ".", ""), 
            $cacheDB->GetDBHits(), $cacheDB->GetCacheHits());

    $db->close();
}
catch(Exception $ex)
{ 
    ob_clean(); 
    echo sprintf("zomg borked - %s", $ex->getMessage());
}

//finally

ob_end_flush();

?>