Commit c5a93bdc396bc0c806d0ddb3086973f19c5bd44e

Authored by Adhidarma Hadiwinoto
1 parent a2a0be1274
Exists in master

Optimasi redis history

Showing 1 changed file with 8 additions and 3 deletions Inline Diff

1 'use strict'; 1 'use strict';
2 2
3 const MAX_HISTORY = 1000;
4
3 const redis = require('redis'); 5 const redis = require('redis');
4 const CircularBuffer = require("circular-buffer"); 6 const CircularBuffer = require("circular-buffer");
5 7
6 const config = require('komodo-sdk/config'); 8 const config = require('komodo-sdk/config');
7 const logger = require('komodo-sdk/logger'); 9 const logger = require('komodo-sdk/logger');
8 10
9 const redisClient = redis.createClient(config.redis || { host: '127.0.0.1' }); 11 const redisClient = redis.createClient(config.redis || { host: '127.0.0.1' });
10 const history = new CircularBuffer(1000); 12 const history = new CircularBuffer(MAX_HISTORY);
11 13
12 const REDIS_KEYWORD = `SHAKIR_SMS_HISTORY_${config.name||'SMS'}`; 14 const REDIS_KEYWORD = `SHAKIR_SMS_HISTORY_${config.name||'SMS'}`;
13 15
14 function fetchFromRedis() { 16 function fetchFromRedis() {
15 redisClient.LRANGE(REDIS_KEYWORD, 0, -1, (err, reply) => { 17 redisClient.LRANGE(REDIS_KEYWORD, 0, -1, (err, reply) => {
16 reply.forEach((el) => { 18 reply.reverse().forEach((el) => {
17 try { 19 try {
18 history.push(JSON.parse(el)); 20 history.push(JSON.parse(el));
19 } catch (e) { 21 } catch (e) {
20 logger.warn(`Error parsing JSON on redis history. ${e.toString()}`); 22 logger.warn(`Error parsing JSON on redis history. ${e.toString()}`);
21 } 23 }
22 }); 24 });
23 logger.info(`History fetched from redis with ${reply.length} items.`); 25 logger.info(`History fetched from redis with ${reply.length} items.`);
24 }) 26 })
25 } 27 }
26 fetchFromRedis(); 28 fetchFromRedis();
27 29
28 function push(item) { 30 function push(item) {
29 redisClient.LPUSH(REDIS_KEYWORD, JSON.stringify(item)); 31 redisClient.LPUSH(REDIS_KEYWORD, JSON.stringify(item), () => {
32 redisClient.LTRIM(REDIS_KEYWORD, 0, MAX_HISTORY);
33 });
34
30 history.push(item); 35 history.push(item);
31 } 36 }
32 37
33 function dump() { 38 function dump() {
34 const result = history.toarray(); 39 const result = history.toarray();
35 // console.log(JSON.stringify(result, null, 2)); 40 // console.log(JSON.stringify(result, null, 2));
36 return result; 41 return result;
37 } 42 }
38 43
39 exports.push = push; 44 exports.push = push;
40 exports.dump = dump; 45 exports.dump = dump;