Last active
January 31, 2021 10:22
-
-
Save Aung-Myint-Thein/d08ead67ee50585ae92f066f1e72e8f7 to your computer and use it in GitHub Desktop.
Redis connection provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Redis = require("ioredis"); | |
const client = new Redis({ | |
host: "redis_host", | |
port: "redis_port", | |
connectTimeout: 2000, | |
lazyConnect: true, | |
maxRetriesPerRequest: 2, | |
reconnectOnError: function(err) { | |
if (err.message.startsWith('READONLY')) { | |
return true | |
} | |
}, | |
retryStrategy: (times) => 2000, | |
}); | |
client | |
.on('error', (e) => { | |
console.log(e) | |
client.disconnect(); | |
}) | |
.on('close', () => { | |
client.disconnect(); | |
}) | |
const getCachedDataByKey = async(key) => { | |
let cachedData = null; | |
if (client.status !== "ready" && client.status !== "wait") { | |
try { | |
await client.connect(); | |
} catch (error) { | |
console.log("getCachedDataByKey CATCH CONNECT"); | |
console.log(error); | |
} | |
} | |
if (client.status === "ready" || client.status === "wait") { | |
try { | |
cachedData = await client.get(key); | |
} catch (error) { | |
console.log("getCachedDataByKey CATCH GET"); | |
console.log(error); | |
} | |
} | |
return JSON.parse(cachedData); | |
} | |
const setDataToCache = async (key, value, EX = 24*60*60) => { | |
if (client.status !== "ready" && client.status !== "wait") { | |
try { | |
await client.connect(); | |
} catch (error) { | |
console.log("setDataToCache CATCH CONNECT"); | |
console.log(error); | |
} | |
} | |
if (client.status === "ready" || client.status === "wait") { | |
try { | |
await client.set(key, JSON.stringify(value), "EX", EX); | |
console.log("setDataToCache TRY Done"); | |
} catch(error) { | |
console.log("setDataToCache CATCH"); | |
console.log(error); | |
} | |
} | |
} | |
module.exports = { | |
getCachedDataByKey, | |
setDataToCache | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment