登录
首页 >  Golang >  Go问答

创建 gRPC 客户端连接使用 WithBlock() 选项与异步启动的 gRPC 服务器时,是否会一直阻塞?

来源:stackoverflow

时间:2024-03-24 18:36:46 454浏览 收藏

在使用 `grpc.WithBlock()` 选项时,异步启动的 gRPC 服务器可能无法立即建立客户端连接。虽然该选项旨在阻止 `grpc.Dial()` 立即返回,但它并不保证在连接建立之前返回错误。当连接字符串无效时,连接可能会无限期挂起,导致测试超时。为了确保在连接错误时捕获错误,可以将 `grpc.FailOnNonTempDialError(true)` 与 `grpc.WithBlock()` 一起使用。

问题内容

我想编写一个单元测试,在其中运行一个临时 grpc 服务器,该服务器在测试中的单独 goroutine 中启动,并在测试运行后停止。为此,我尝试将本教程(https://grpc.io/docs/languages/go/quickstart/)中的“hello,world”示例改编为一个服务器和客户端分开的示例main.gos,有一个测试函数,它异步启动服务器,然后使用 grpc.withblock() 选项建立客户端连接。

我已将简化的示例放入此存储库中,https://github.com/kurtpeek/grpc-helloworld;这是 main_test.go

package main

import (
    "context"
    "fmt"
    "log"
    "net"
    "testing"
    "time"

    "github.com/stretchr/testify/require"
    "google.golang.org/grpc"
    "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
    port = ":50051"
)

type server struct {
    helloworld.unimplementedgreeterserver
}

func (s *server) sayhello(ctx context.context, in *helloworld.hellorequest) (*helloworld.helloreply, error) {
    log.printf("received: %v", in.getname())
    return &helloworld.helloreply{message: "hello " + in.getname()}, nil
}

func testhelloworld(t *testing.t) {
    lis, err := net.listen("tcp", port)
    require.noerror(t, err)

    s := grpc.newserver()
    helloworld.registergreeterserver(s, &server{})
    go s.serve(lis)
    defer s.stop()

    log.println("dialing grpc server...")
    conn, err := grpc.dial(fmt.sprintf("localhost:%s", port), grpc.withinsecure(), grpc.withblock())
    require.noerror(t, err)
    defer conn.close()
    c := helloworld.newgreeterclient(conn)

    ctx, cancel := context.withtimeout(context.background(), time.second)
    defer cancel()

    log.println("making grpc request...")
    r, err := c.sayhello(ctx, &helloworld.hellorequest{name: "john doe"})
    require.noerror(t, err)
    log.printf("greeting: %s", r.getmessage())
}

问题是当我运行这个测试时,它超时了:

> go test -timeout 10s ./... -v
=== RUN   TestHelloWorld
2020/06/30 11:17:45 Dialing gRPC server...
panic: test timed out after 10s

我无法理解为什么未建立连接?在我看来,服务器已正确启动...


解决方案


您在此处发布的代码似乎有一个拼写错误:

fmt.sprintf("localhost:%s", 端口)

如果我在没有 grpc.withblock() 选项的情况下运行您的测试函数,c.sayhello 会给出以下错误:

rpc error: code = unavailable desc = connection error: desc = "transport: error while dialing dial tcp: address localhost::50051: too many colons in address"

罪魁祸首似乎是 localhost::50051

const 声明(或者从 fmt.sprintf("localhost:%s", port),如果您愿意的话)中删除额外的冒号后,测试通过。

const (
    port = "50051" // without the colon
)

输出:

2020/06/30 23:59:01 dialing grpc server...
2020/06/30 23:59:01 making grpc request...
2020/06/30 23:59:01 received: john doe
2020/06/30 23:59:01 greeting: hello john doe

但是,从grpc.withblock()的文档来看

如果没有这个,dial 会立即返回并在后台连接服务器。

因此,使用此选项,任何连接错误都应立即从 grpc.dial 调用返回:

conn, err := grpc.dial("bad connection string", grpc.withblock()) // can't connect
if err != nil {
    panic(err) // should panic, right?
}

那么为什么你的代码会挂起?

通过查看 grpc 包的源代码(我针对 v1.30.0 构建了测试):

// a blocking dial blocks until the clientconn is ready.
    if cc.dopts.block {
        for {
            s := cc.getstate()
            if s == connectivity.ready {
                break
            } else if cc.dopts.copts.failonnontempdialerror && s == connectivity.transientfailure {
                if err = cc.connectionerror(); err != nil {
                    terr, ok := err.(interface {
                        temporary() bool
                    })
                    if ok && !terr.temporary() {
                        return nil, err
                    }
                }
            }
            if !cc.waitforstatechange(ctx, s) {
                // ctx got timeout or canceled.
                if err = cc.connectionerror(); err != nil && cc.dopts.returnlasterror {
                    return nil, err
                }
                return nil, ctx.err()
            }
        }

所以 s 此时确实处于 transientfailure 状态,但是 failonnontempdialerror 选项默认为 false,并且 waitforstatechange 在上下文过期时为 false,这不会发生,因为 zqbczq bdial 在后台上下文中运行:

// dial creates a client connection to the given target.
func dial(target string, opts ...dialoption) (*clientconn, error) {
    return dialcontext(context.background(), target, opts...)
}

此时我不知道这是否是预期行为,因为从 v1.30.0 开始,其中一些 api 被标记为实验性的。

无论如何,最终为了确保您在 dial 上捕获此类错误,您还可以将代码重写为:

conn, err := grpc.Dial(
        "localhost:50051", 
        grpc.WithTransportCredentials(insecure.NewCredentials()),
        grpc.FailOnNonTempDialError(true),
        grpc.WithBlock(), 
    )

如果连接字符串错误,则会立即失败并显示相应的错误消息。

今天关于《创建 gRPC 客户端连接使用 WithBlock() 选项与异步启动的 gRPC 服务器时,是否会一直阻塞?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>