【问题标题】:Golang gRPC can't keep alive: the client connection is closingGolang gRPC 无法保持活动状态:客户端连接正在关闭
【发布时间】:2020-10-07 23:58:39
【问题描述】:

您好,我正在尝试将 gRPC 客户端连接到服务器,但即使连接成功,我在从 graphql 解析器查询它时也会收到以下错误。但是,如果我直接从解析器拨号,一切正常,所以它与客户端不保持连接打开有关。

rpc 错误:代码 = 已取消 desc = grpc:客户端连接正在关闭

client.go

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 back
    PermitWithoutStream: true,             // send pings even without active streams
}

func gqlHandler() http.HandlerFunc {

    conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure(), 
    grpc.WithKeepaliveParams(kacp),
    grpc.WithBlock())

    if err != nil {
        panic(err)
    }
    defer conn.Close()

    db := proto.NewPlatformDBClient(conn)

    gh := handler.GraphQL(platform.NewExecutableSchema(platform.Config{Resolvers: &platform.Resolver{
        DB: db,
    }}))

    gh = cors.Disable(gh)

    return gh
}

【问题讨论】:

  • 我有一个类似的问题,但有一个 Kotlin for Android 客户端。您能找到保持连接打开的任何解决方案吗?

标签: go graphql grpc


【解决方案1】:

因为 defer conn.Close() 命令将在连接使用之前执行。

From the go blog

defer 语句将函数调用推送到列表中。名单 保存的调用在周围函数返回后执行。

因此您将删除defer conn.Close() 行并在不再使用后关闭连接。

【讨论】:

    【解决方案2】:

    请检查连接是否不为零,然后继续关闭它。

    根据 close() 中定义的错误,如果连接为 nil,则会发生 ErrClientConnClosing 错误。

    代码参考:https://github.com/grpc/grpc-go/blob/master/clientconn.go#L1064

    if c.conn != nil { errs := c.Close() }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 2021-05-02
      • 2020-10-25
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多