将上下文从gRPC端点传递到goroutine时收到上下文取消错误



我正试图将上下文从传入的gRPC端点传递给goroutine,goroutine负责向外部服务发送另一个请求,但我从goroutine中的ctxhttp.Get函数调用接收到Error occurred: context canceled

package main
import (
"fmt"
"net"
"net/http"
"os"
"sync"
"golang.org/x/net/context/ctxhttp"
dummy_service "github.com/myorg/testing-apps/dummy-proto/gogenproto/dummy/service"
"github.com/myorg/testing-apps/dummy-proto/gogenproto/dummy/service/status"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
func main() {
var err error
grpcServer := grpc.NewServer()
server := NewServer()
dummy_service.RegisterDummyServer(grpcServer, server)
reflection.Register(grpcServer)
lis, err := net.Listen("tcp", ":9020")
if err != nil {
fmt.Printf("Failed to listen: %+v", err)
os.Exit(-1)
}
defer lis.Close()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Starting gRPC Server")
if err := grpcServer.Serve(lis); err != nil {
fmt.Printf("Failed to serve gRPC: %+v", err)
os.Exit(-1)
}
}()
wg.Wait()
}
type server struct{}
func NewServer() server {
return server{}
}
func (s server) Status(ctx context.Context, in *status.StatusRequest) (*status.StatusResponse, error) {
go func(ctx context.Context) {
client := http.Client{}
// it's important to send the ctx from the parent function here because it contains
// a correlation-id which was inserted using grpc middleware, and the external service
// prints this value in the logs to tie everything together
if _, err := ctxhttp.Get(ctx, &client, "http://localhost:4567"); err != nil {
fmt.Println("Error encountered:", err)
return
}
fmt.Println("No error encountered")
}(ctx)
response := status.StatusResponse{
Status: status.StatusResponse_SUCCESS,
}

// if I enable the following, everything works, and I get "No error encountered"
// time.Sleep(10 * time.Millisecond)
return &response, nil
}

如果我在调用函数中添加一个time.Sleep(),goroutine就会按预期成功,不会收到任何错误。似乎父函数的上下文一返回就被取消了,而且由于父函数在goroutine之前结束,所以传递给goroutine的上下文接收到context canceled错误。

我意识到我可以通过让调用函数等待goroutine完成来解决这个问题,这可以防止上下文被取消,但我不想这样做,因为我希望函数立即返回,以便到达端点的客户端尽快得到响应,同时goroutine在后台继续处理。

我也可以通过不使用传入的ctx来解决这个问题,而是在我的goroutine中使用context.Background()。然而,我想使用传入ctx,因为它包含一个由grpc中间件插入的correlation-id值,需要作为goroutine发出的传出请求的一部分传递,以便下一个服务器可以在其日志消息中打印该CCD_ 9以将请求绑定在一起。

我最终通过从传入上下文中提取correlation-id并将其插入goroutine中的新context.Background()来解决这个问题,但我想避免这种情况,因为它在goroutine发出的每个传出请求周围添加了一堆样板代码,而不仅仅是能够传递上下文。

有人能向我解释为什么上下文被取消,并让我知道是否有针对这种情况的"最佳实践"解决方案吗?是否不可能在具有gRPC的goroutine中使用从调用函数传入的上下文?

@adamc如果您还没有找到任何其他方法。

我最终得到了这个解决方案(也不完美(只复制完整的上下文。但我更喜欢这样做,而不是手动将原始上下文中的值添加到context.Background

md, _ := metadata.FromIncomingContext(ctx)
copiedCtx := metadata.NewOutgoingContext(context.Background(), md)

最新更新