gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:53:43 25 4
gpt4 key购买 nike

所以我才刚刚开始使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com