第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

NodeJS Redis - 在后臺(tái)重新連接

NodeJS Redis - 在后臺(tái)重新連接

瀟瀟雨雨 2023-03-24 14:38:16
我的情況是 - 我正在嘗試通過(guò) REDIS 密鑰檢索資源。如果密鑰不存在,則從 API 獲取它。遇到一個(gè)問(wèn)題,如果 Redis 連接斷開(kāi)或者我無(wú)法從啟動(dòng)連接到 Redis,那么 nodejs 庫(kù)('redis')將繼續(xù)嘗試重新連接。它阻止我通過(guò) API 獲取我需要的信息,因?yàn)橹卦囘壿媽⒔庸懿⑶也粫?huì)繼續(xù)獲取所需信息。我希望此功能在后臺(tái)運(yùn)行 - 可能嗎?意思是,如果 Redis 關(guān)閉/無(wú)法從 NodeJs 連接到 REDIS,那么它將嘗試重新連接。然而,當(dāng)它關(guān)閉并且應(yīng)用程序?qū)L試定期重新連接時(shí),我希望能夠通過(guò)備份計(jì)劃獲取數(shù)據(jù),即通過(guò) API,正如我上面提到的。任何關(guān)于這種情況的指示將不勝感激 - 在此先感謝您。
查看完整描述

1 回答

?
莫回?zé)o

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)

});


查看完整回答
反對(duì) 回復(fù) 2023-03-24
  • 1 回答
  • 0 關(guān)注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)