0

我有friendship_request数据库表,如果这个表有一百万条记录,当我尝试搜索关于tom的请求时,实际上在这百万条记录中没有对tom的友谊请求,所以哪个更好:索引到在内存缓存中,当有人向 tom 发送请求时,然后首先尝试检查内存缓存中的 tom,因此如果存在,请转到数据库并进行搜索查询。或者直接进行搜索查询而不首先检查内存缓存哪个更快?谢谢

4

1 回答 1

2

首先检查 Memcache会更快。就像名称一样,项目存储在内存中,并且比数据库查找具有更少的 I/O。但是,如果服务器的 RAM 已满,Memcached 将驱逐所有数据。出于这个原因,假设放入 Memcache中的任何数据仍然存在是不明智的。甚至在项目的时间到期之前。

大多数 Memcache 包装器和 API 将返回 FALSE 或 NOT_FOUND。因此,您的应用程序只需要确定您请求的项目是否已存储,如果没有,请检查数据库。完成数据库搜索后,只需在 Memcached中记录结果或没有结果。这将防止您的应用程序再次重新运行相同的搜索。

这是与 Memcached 的快速交互

shell ~> telnet localhost 11211
tel ~> get tom
       NOT_FOUND

tel ~> set tom 0 86400 5
    ~> 1,2,3
       STORED

tel ~> get tom
       VALUE tom 0 5
       1,2,3
       END

还有一个快速的 PHP 小类示例

<?php
class FriendshipRequest extends Memcache {

    const KEY_PREFIX = 'fr_' ; // Use constant prefix to create namespace
    const FLAG = 0;            // Flag for memechache storage option
    const EXPIRE = 86400;      // Store for one day

    public function __construct() {
    $this->addServer('localhost',11211);
    }

    public function __destruct() {
        $this->close();
    }

    /**
     * Find a name
     *
     * First check memcached. If not found,
     * search database, and store results
     * in a JSON string
     *
     * @param string $name
     * @return array
     */
    public function find($name) {
            $key = $this->toKey($name);
            $results = $this->get($key);
            if( $results === false ) {
                    $results = $this->databaseSearch($name);
                    $this->set($key,json_encode($results),self::FLAG,self::EXPIRE);
            } else {
                    $results = json_decode($results);
            }
            return $results;
    }

    /**
     * Run a database search, and return array of matching ID's
     * @param string $name
     * @return array
     */
    private function databaseSearch($name) {
            $sql = sprintf('SELECT `friend_id` FROM `friendship_request` WHERE `friend_name` LIKE "%s"', mysql_real_escape_string($name));
            $matches = array();
            // Database connection omitted
            $results = mysql_query($sql);
            while( $row = mysql_fetch_object($results) ) {
             array_push($matches,$results->friend_id);
            }
            mysql_free_result($results);
            return $matches;
    }

    /**
     * Create a namespace for key
     * @param string $name
     * @return string
     */
    private function toKey($name) {
            return self::KEY_PREFIX.sha1($name);
    }
}
于 2012-07-26T16:38:11.647 回答