mysql-sender.js
937 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const client = require('./mysql-client');
const logger = global.yoho.logger;
class MySqlSender {
constructor(table, duration = 2000) {
this.table = table;
this.batchMessages = [];
setInterval(() => {
this._send();
}, duration);
}
addMessage(msg) {
if (msg) {
this.batchMessages.push(msg);
}
}
async _send() {
const len = this.batchMessages.length;
if (len < 1) {
logger.debug('[db] insert list is empty');
return;
}
const bulk = this.batchMessages.splice(0, len);
for (let i of bulk) {
logger.debug('[db] insert db [%s]', JSON.stringify(i));
await client(this.table).insert(i).catch((err) => {
logger.error('[db] insert data=[%s] error=[%s]', JSON.stringify(i), err);
});
}
}
}
module.exports = MySqlSender;