var config = require('./config');
var net = require('net');
var mysql_driver = require('mysql');
var mysql = mysql_driver.createConnection(config.db);
mysql.connect();
var cache = {};
// Build the cache
var csql = "SELECT * FROM (SELECT accountID, deviceID, uniqueID FROM Device ORDER BY uniqueID DESC) sub GROUP BY uniqueID";
mysql.query(csql, function(err, rows, fields) {
for (key in rows) {
cache[rows[key].uniqueID] = {};
cache[rows[key].uniqueID].accountID = rows[key].accountID;
cache[rows[key].uniqueID].deviceID = rows[key].deviceID;
}
});
运行这个udp-parse.js后,如果在运行期间,接收到缓存里没有的uniqueID,会导致udp-parse.js程序停止运行,不知道可否定期查询一下上面的代码。
var account = cache[datum.uniqueID].accountID; ^ TypeError: Cannot read property ‘accountID’ of undefined at Socket.recvMsg (/home/node/NodeJS-Server/udp-parse.js:170:54) at Socket.EventEmitter.emit (events.js:99:17) at UDP.onMessage (dgram.js:353:8) DEBUG: Program node udp-parse.js exited with code 1
DEBUG: Starting child process with ‘node udp-parse.js’
got message from 119.142.84.130:10000
这个属于代码结构不严谨的原因,如果没有,你可以返回一个空对象而不是定期查询将简单的事情复杂化例如这样:
var account = datum.uniqueID ? (cache[datum.uniqueID].accountID ? cache[datum.uniqueID].accountID : {}) : {};
如果不查询的话,在JS运行期间,系统新增的帐号就不能查到并写入定位数据,因为数据库表的主键有3个,所以必须查DeviceID表才能查 accountID和deviceID。
谢谢你的回复。
那你可以用下kue,npm install kue,将你上面那段代码变成一个job,设置时间定期去执行,地址:https://github.com/LearnBoost/kue
差点忘说了,至于定时可以用cron这个lib去做,https://github.com/ncb000gt/node-cron, 设置定时去执行你用kue做成的job
找个一个简单的办法:
var minutes = 1, the_interval = minutes * 60 * 1000;
setInterval(function() {
console.log("query db account every 1 min");
var csql = "SELECT * FROM (SELECT accountID, deviceID, uniqueID,smsEmail FROM Device ORDER BY uniqueID DESC) sub GROUP BY uniqueID";
mysql.query(csql, function(err, rows, fields) {
for (key in rows) {
cache[rows[key].uniqueID] = {};
cache[rows[key].uniqueID].accountID = rows[key].accountID;
cache[rows[key].uniqueID].deviceID = rows[key].deviceID;
cache[rows[key].uniqueID].smsEmail = rows[key].smsEmail;
}
});
}, the_interval);