1 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以圍繞您的 redis 連接創(chuàng)建一個(gè)包裝器/代理,以確保所有 redis 操作都連接了 redis。如果不是,您可以拋出一個(gè)錯(cuò)誤(您可以在調(diào)用者中處理)或返回未定義。
基本上,您可以偵聽(tīng)ready和error事件并更新status該包裝器內(nèi)的 - 標(biāo)志,以便始終了解當(dāng)前的連接狀態(tài)。
現(xiàn)在,這肯定會(huì)涵蓋初始連接不成功或調(diào)用之間發(fā)生斷開(kāi)連接的情況。問(wèn)題是在您status成功檢查 -flag 后斷開(kāi)連接的罕見(jiàn)情況。要解決這個(gè)問(wèn)題,您可以為 redis 調(diào)用定義一個(gè)最長(zhǎng)等待時(shí)間,如果達(dá)到超時(shí)則返回/拋出錯(cuò)誤并忽略 redis 結(jié)果。下面是一些可以幫助您入門(mén)的基本代碼:
class RedisService {
isConnected = false;
client;
constructor() {
this.client = redis.createClient();
this.client.get = promisify(this.client.get).bind(this.client);
this.client.set = promisify(this.client.set).bind(this.client);
this.attachHandlers();
}
attachHandlers() {
this.client.on("ready", () => {
this.isConnected = true;
});
this.client.on("error", (err) => {
this.isConnected = false;
console.log(err);
});
}
async tryGet(key) {
if (!this.isConnected) {
return undefined; // or throw an error
}
return Promise.race([this.client.get(key), this.wait()]);
}
async trySet(key, val) {
if (!this.isConnected) {
return undefined; // or throw an error
}
return Promise.race([this.client.set(key, val), this.wait()]);
}
wait(ms = 200) {
return new Promise(resolve => {
setTimeout(resolve, ms);
})
}
}
然后在你的來(lái)電者中你可以這樣做:
async someMethodThatCallsRedisOrApi() {
let result;
try {
result = await redisService.tryGet('testkey');
} catch (e) {
console.log(e);
}
if (!result) {
result = apiService.get(...); // call the actual api to get the result
await redisService.trySet('testkey', result);
}
res.json(result)
});
添加回答
舉報(bào)