【发布时间】:2011-11-17 23:39:05
【问题描述】:
我正在寻找减少在我的 MySQL 服务器上执行的查询数量的方法。
应用程序和数据库服务器位于不同的机器上,因此在应用程序服务器上缓存以前的查询结果似乎不是一个糟糕的选择。显然还有其他策略,例如减少查询数量和优化查询语句,但我认为我不应该将查询缓存作为一种选择。
我最初认为我可以轻松地在 Zend_Db 对象中打开某种形式的查询缓存,但是我最接近看到横切的东西是 Zend_Db_Profiler。
我正在考虑的一种方法是为我的Zend_Db_Adapter 对象创建一个代理。大意是:
/**
* Initialize the database.
*
* @return void
*/
protected function _initDb() {
// Instantiate a connection to the database
$config = Zend_Registry::get('config');
$db = new MyProject_Db_Proxy (
Zend_Db::factory($config->resources->db->adapter,
$config->resources->db->params)
);
// Store the database object in the registry
Zend_Registry::set('db', $db);
Zend_Db_Table::setDefaultAdapter('db');
}
我查看了各种Zend_Db 接口和类,看起来我可以通过代理将缓存注入Zend_Db_Adapter_Abstract::query() 方法。大意是:
public MyProject_Db_Proxy() {
private $_adapter = null;
...
public function query($sql, $bind = array()) {
// Generate the cache key by joining and hashing $sql and $bind
// Check to see if key is in cache, return if found
// Execute query
$stmt = this->_adapter->query($sql, $bind);
// Cache result
}
...
}
我的问题是:有没有更好/更简单的方法将缓存注入 Zend_Db?
【问题讨论】:
-
启用您的数据库查询缓存。
-
请注意,我使用的是 Zend Framework 1.11.11 和 PDO MySQL 适配器。
-
@hakre 您是否建议数据库查询缓存将摆脱网络往返?你能指点我这方面的资源吗?
-
不,它不会用于网络往返。如果要防止网络往返,需要客户端查询缓存,见forge.mysql.com/wiki/MySQLnd_Query_Cache_Plugin_for_PHP
-
@hakre 我会记住这个插件。它相当新,可能需要升级数据库,但它可能是一种选择。
标签: php zend-framework caching