简体   繁体   English

限制大型查询上的数据库流量的最佳方法?

[英]Best approach to limit database traffic on large query?

I have a database that i'm dealing with which is updated every few hours remotely (not on any specific time span) and i have no control over the administration of it. 我有一个正在处理的数据库,该数据库每隔几个小时会远程更新一次(而不是在任何特定时间范围内),并且我无法控制它的管理。 I have web clients connecting to it to view information contained within it. 我有连接到它的Web客户端以查看其中包含的信息。 These clients (coded using PHP and Javascript) might be checking the database very often (impatient users) even though there may not be any change to the database itself and the check will involve quite a lengthy query involving lots of lookups and cross referencing, etc. 这些客户端(使用PHP和Javascript编码)可能会经常检查数据库(不耐烦的用户),即使数据库本身可能没有任何变化,并且检查将涉及相当长的查询,涉及大量查找和交叉引用等。 。

So in order to cut down on database queries and to keep things snappy what would be the best way to limit the number of times the clients will actually run the whole query on the database? 因此,为了减少数据库查询并使事情保持活泼,什么是最好的方法来限制客户端实际在数据库上运行整个查询的次数?

To make things crystal clear, i have no way of altering the database, i can only query it. 为了使事情变得清晰起来,我无法更改数据库,我只能查询它。 But i have full control over the source of the web client. 但是我完全可以控制Web客户端的来源。

You should use some sort of cache. 您应该使用某种缓存。 For more serious sites, take a look at memcached. 对于更严重的网站,请看一下memcached。 If you are in a smaller scale, cache the results to file by serializing it. 如果规模较小,请通过序列化将结果缓存到文件中。

I would take a look at Zend_Cache . 我来看看Zend_Cache

Each query will only run once for the lifetime of the cache (which can be easily changed). 每个查询在缓存的整个生命周期内仅运行一次(可以轻松更改)。 Sessions aren't a viable solution since the same query will run at least once per user. 会话不是可行的解决方案,因为每个用户至少要运行一次相同的查询。 Sessions can also be easily renewed. 会话也可以轻松更新。

You'll want to check if the result set exists in the cache. 您将要检查结果集是否存在于缓存中。 If not, cache the result set with a unique identifier: 如果不是,请使用唯一标识符缓存结果集:

$query = "SELECT * FROM really_big_table";
$cache_query = md5($query);
if(!$result = $cache->load($cache_query))
{
     $result = $db->fetchAll($query);
     $cache->save($result, $cache_query);
}

By using a cache you are setting your own time frame for when data is updated for all users. 通过使用缓存,您可以为所有用户更新数据的时间设置自己的时间范围。

Do you have control over the web app? 您可以控制网络应用程序吗? If users are logged in and have sessions associated with them, you could cache the time since a user last queried the database, and refuse to hand back new data if a request is beneath some threshold interval since the last query. 如果用户已登录并具有与之相关联的会话,则可以缓存自用户上次查询数据库以来的时间,如果请求自上次查询以来处于某个阈值间隔以下,则可以拒绝交出新数据。

PHP Sessions PHP会话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM