mysql - 我应该避免建立 MySQL 连接(使用 Memcache 时)还是无论如何都要建立连接?

标签 mysql optimization memcached

所以我才刚刚开始使用 Memcache。我准备编写一些代码,但是我有一个优化问题:

我想知道我是否应该尽可能延迟建立一个 MySQL Connect(并且可能根本不建立一个,当所有内容都可以从 Memcache 中读取时)或者无论如何建立它以节省我的编码时间,基于这样的想法不是连接而是实际查询让我的服务器的 CPU 发疯。

所以,我必须在这两个代码示例之间做出选择:

1 - 仍然连接到 MySQL

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("MEMCACHE: Could not connect!");
$db = mysql_connect('localhost', 'user', 'password') or die ("MySQL: Could not connect!");
mysql_select_db('database');

$sql = "SELECT id FROM table LIMIT 1";
$key = md5('query'.$sql);
//lookup value in memcache
$result = $memcache->get($key);
//check if we got something back
if($result == null) {
//fetch from database
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
if(mysql_num_rows($qry)> 0) {
    $result = mysql_fetch_object($qry);
    //store in memcache for 60 seconds
    $memcache->set($key,$result,0,60);
   }
}

2 - 在需要时立即连接到 MySQL

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

$sql = "SELECT id FROM table LIMIT 1";
$key = md5('query'.$sql);
//lookup value in memcache
$result = $memcache->get($key);
//check if we got something back
if($result == null) {

if(!$db){
    $db = mysql_connect('localhost', 'user', 'password') or die ("MySQL: Could not connect!");
    mysql_select_db('database');
}

//fetch from database
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
if(mysql_num_rows($qry)> 0) {
    $result = mysql_fetch_object($qry);
    //store in memcache for 60 seconds
    $memcache->set($key,$result,0,60);
   }
}

最佳答案

方法是仅在需要时才连接到 mySQL(和其他东西)。这样你就可以减少你的应用程序在这种情况下网络连接所需的资源。并且您不会给数据库服务器带来负载。

一般经验法则:仅在需要时使用资源。

关于mysql - 我应该避免建立 MySQL 连接(使用 Memcache 时)还是无论如何都要建立连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011231/

相关文章:

Django:使 ModelChoiceField 在运行时评估查询集

mysql - 使用 MongoDb 的数据库结构

mysql - 错误 1005 (HY000) : Can't create table db. #sql-5471_137' (errno: 121)

c# - 为什么这个 IEnumerable 扩展方法比另一个(更简单的)扩展方法(只迭代输入)慢得多?

c++ - header 实现和用于优化的内联关键字

java - Spring MemCached 刷新所有奇怪的行为

MySQL 连接在 vb6 上获取 "Run-time error -2147467259 (80004005)"但适用于 VBA Excel

Ubuntu 服务器上的 Mysql 服务器比 Ubuntu 桌面慢

c++ - 为什么在 XCode 中默认情况下循环展开?

caching - Docker:如何在容器中安装memcached