golang grpc keepalive

最近遇到 grpc 客戶端報(bào)錯(cuò) rpc error: code = Unavailable desc = transport is closing,原因是連接長(zhǎng)時(shí)間沒(méi)有使用,被服務(wù)端斷開(kāi),這種情況通過(guò)簡(jiǎn)單粗暴的重試策略可以解決,更加優(yōu)雅的解決方案是增加保持連接策略

服務(wù)端

var kaep = keepalive.EnforcementPolicy{
    MinTime:             5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection
    PermitWithoutStream: true,            // Allow pings even when there are no active streams
}

var kasp = keepalive.ServerParameters{
    MaxConnectionIdle:     15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY
    MaxConnectionAge:      30 * time.Second, // If any connection is alive for more than 30 seconds, send a GOAWAY
    MaxConnectionAgeGrace: 5 * time.Second,  // Allow 5 seconds for pending RPCs to complete before forcibly closing connections
    Time:                  5 * time.Second,  // Ping the client if it is idle for 5 seconds to ensure the connection is still active
    Timeout:               1 * time.Second,  // Wait 1 second for the ping ack before assuming the connection is dead
}

server := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp))

客戶端

var kacp = keepalive.ClientParameters{
    Time:                10 * time.Second, // send pings every 10 seconds if there is no activity
    Timeout:             time.Second,      // wait 1 second for ping ack before considering the connection dead
    PermitWithoutStream: true,             // send pings even without active streams
}

conn, err := grpc.Dial(*addr, grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp))

鏈接

轉(zhuǎn)載請(qǐng)注明出處
本文鏈接:https://tech.hatlonely.com/article/52

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.簡(jiǎn)介 在gRPC中,客戶端應(yīng)用程序可以直接調(diào)用不同計(jì)算機(jī)上的服務(wù)器應(yīng)用程序上的方法,就像它是本地對(duì)象一樣,使您...
    第八共同體閱讀 2,099評(píng)論 0 6
  • 在微服務(wù)架構(gòu)里面,每個(gè)小服務(wù)都是由很多節(jié)點(diǎn)組成,節(jié)點(diǎn)的添加刪除故障希望能對(duì)下游透明,因此有必要引入一種服務(wù)的自動(dòng)注...
    hatlonely閱讀 2,621評(píng)論 0 7
  • gRPC 是一個(gè)高性能、通用的開(kāi)源RPC框架,基于HTTP/2協(xié)議標(biāo)準(zhǔn)和Protobuf序列化協(xié)議開(kāi)發(fā),支持眾多的...
    小波同學(xué)閱讀 19,816評(píng)論 6 19
  • 1)簡(jiǎn)介 gRPC負(fù)載平衡的主要實(shí)現(xiàn)機(jī)制是外部負(fù)載平衡,即通過(guò)外部負(fù)載平衡器來(lái)向客戶端提供更新后的服務(wù)器列表。 g...
    Jay_Guo閱讀 13,645評(píng)論 6 22
  • 文 / 袁非 當(dāng)你從初中課本走下來(lái)闖入我的記憶 我就知道我已為你種下一世的因果 只是選在九月造訪 有些辜負(fù)你三十年...
    袁非非也閱讀 737評(píng)論 13 18

友情鏈接更多精彩內(nèi)容