LoginSignup
1
0

More than 3 years have passed since last update.

14rep - gRPC クライアントの keepalive 自分メモ用

Posted at

書いた理由

  • gRPC Serverは書いたがClientは書いたことないな....と思い自分メモ

keepalive は 2 種類

TCP レイヤーの keepalive

  • これは TCP ソケットの SO_KEEPALIVE オプション
  • 細かい設定をアプリケーションから行えないので、アプリケーションレイヤーの実装が提供されている

アプリケーションレイヤーの keepalive

  • http/2 の PING フレームを定期的に送ってタイムアウトしたら再接続する
  • クライアントのバッテリーや DDos 配慮のため、アクティブなストリームがない場合は PING フレームを送らないオプションが提供されている
package client

import (
    "log"
    "time"

    "google.golang.org/grpc"
    "google.golang.org/grpc/keepalive"
)

const (
    // GRPCClientKeepaliveTime 活動がなくなってから PING を送るまでの間隔を表す。
    GRPCClientKeepaliveTime = 2 * time.Second
    // GRPCClientKeepaliveTimeout PING 応答を待つ時間を表す。
    GRPCClientKeepaliveTimeout = 2 * time.Second
)

// TLS通信しない
// GrpcCliCon gRPC Client 接続
func GrpcCliCon() (*grpc.ClientConn, error) {
    addr := "host.docker.internal:3010"
    conn, err := grpc.Dial(addr,
        grpc.WithInsecure(),
        grpc.WithKeepaliveParams(keepalive.ClientParameters{
            Time:                GRPCClientKeepaliveTime,    // 活動がなくなってから PING を送るまでの間隔
            Timeout:             GRPCClientKeepaliveTimeout, // PING 応答を待つ時間
            PermitWithoutStream: true,                       // アクティブなストリームがないときも probe を送るかどうか
        }),
    )
    if err != nil {
        log.Fatal("client gRPC Dial connection error:", err)
    }
    return conn, nil
}

grpc.WithInsecure()

func WithInsecure() DialOption
  • WithInsecure は、この ClientConn のトランスポートセキュリティを無効にすDialOption を返します。
  • WithInsecure が設定されていない限り、トランスポートセキュリティが必要です。

Client接続

  • go用に吐かれたgRPCファイル内に{xxxxServiceClient}と書かれた内容を見つけてください
sc := pb.New{gRPCを参照}ServiceClient(conn) // 作成されたgRPCファイルを参照してください
req := &pb.HogeFugeRequest{
    RequestId: requestID,
    Name: c.Query("word"),
}

res, _ := sc.SampleHoge(ctx, req)
    if res.Status.Code != int32(pb.Code_OK) {
        c.JSON(getStatusCode(res.Status.Code), res)

        return
    }

参考記事

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0