From c5a93bdc396bc0c806d0ddb3086973f19c5bd44e Mon Sep 17 00:00:00 2001 From: Adhidarma Hadiwinoto <me@adhisimon.org> Date: Tue, 30 Jul 2019 22:38:17 +0700 Subject: [PATCH] Optimasi redis history --- lib/history.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/history.js b/lib/history.js index c5240d8..5468ed8 100644 --- a/lib/history.js +++ b/lib/history.js @@ -1,5 +1,7 @@ 'use strict'; +const MAX_HISTORY = 1000; + const redis = require('redis'); const CircularBuffer = require("circular-buffer"); @@ -7,13 +9,13 @@ const config = require('komodo-sdk/config'); const logger = require('komodo-sdk/logger'); const redisClient = redis.createClient(config.redis || { host: '127.0.0.1' }); -const history = new CircularBuffer(1000); +const history = new CircularBuffer(MAX_HISTORY); const REDIS_KEYWORD = `SHAKIR_SMS_HISTORY_${config.name||'SMS'}`; function fetchFromRedis() { redisClient.LRANGE(REDIS_KEYWORD, 0, -1, (err, reply) => { - reply.forEach((el) => { + reply.reverse().forEach((el) => { try { history.push(JSON.parse(el)); } catch (e) { @@ -26,7 +28,10 @@ function fetchFromRedis() { fetchFromRedis(); function push(item) { - redisClient.LPUSH(REDIS_KEYWORD, JSON.stringify(item)); + redisClient.LPUSH(REDIS_KEYWORD, JSON.stringify(item), () => { + redisClient.LTRIM(REDIS_KEYWORD, 0, MAX_HISTORY); + }); + history.push(item); } -- 1.9.0