简体   繁体   English

使用cronjob更新和显示MySQL查询的结果

[英]Using a cronjob to update and display results of a MySQL query

Im having some trouble how I could realize it to have a dynamic website where the data is fetched via ajax to the user. 我在如何实现一个动态网站方面遇到了麻烦,该网站通过ajax将数据提取给用户。

At the end of the ajax is a simple php script which opens a MySQL connection to my db and fetching some results (which looks to all users the same, there aren't any user specific results) to display them later for example in a table. 在ajax的末尾是一个简单的php脚本,该脚本打开一个与我的数据库的MySQL连接并获取一些结果(对所有用户而言都是相同的,没有任何特定于用户的结果),以便稍后在表中显示它们。

This is what I come so far. 这就是我到目前为止的事情。 It is working but when there thousands of users who open the website ... this wouldn't be good and I don't think my server would update it fast enough. 它正在运行,但是当成千上万的用户打开该网站时……这不好,而且我认为我的服务器更新得不够快。

So my intention is to update the wanted results only once every x seconds serversided with a cronjob maybe, I would save a lot resources. 因此,我的意图是每隔x秒仅更新一次所需的结果,并且可能会节省很多资源。

The problem is that I don't know how I could realize this part, could I please get some help? 问题是我不知道该如何实现这一部分,请问能得到一些帮助吗? Or should I forget the ajax stuff and start using node.js? 还是我应该忘记Ajax的东西并开始使用node.js?

I've got a pretty good root server which is my webspace aswell so it would be possible to install some extra applications. 我有一个相当不错的根服务器,它也是我的网站空间,因此可以安装一些额外的应用程序。

A really basic Node.js solution using memory-cache and node-cron : 一个真正的使用memory-cachenode-cron Node.js解决方案:

var cache = require('memory-cache');
var CronJob = require('cron').CronJob;

var job;
var jobStarted = false;
var rateLimitExceeded = false;

var job = new CronJob('5 * * * * *', function() {
    // Runs every 5 seconds
    doALongDataBaseOperation(function(err, data) {
        cache.put('cacheId', data);
    });
});

app.get('/path/that/needs/caching', function(req, res) {
    cache.get('cacheId', function(e, data) {
        if (data) {
            res.end(data);
        } else {
            // contingency in case the cache doesn't exist
            doALongDataBaseOperation(function(err, data) {
                res.end(data);
                cache.put('cacheId', data);
            });
        }
    });
});

You could cache the data using Memcache (or something similar). 您可以使用Memcache(或类似的东西)来缓存数据。 Your cronjob could run and refresh the cache as often as you would like. 您的cronjob可以根据需要运行和刷新缓存。

Then your AJAX can call a simple PHP script to retrieve the data from your cache. 然后,您的AJAX可以调用一个简单的PHP脚本以从缓存中检索数据。

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

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