ZBLOG

golang grpc client set each call timeout and add metadata

To set a timeout for each gRPC call and add metadata to the client, you can use the context.WithTimeout function and the metadata.NewOutgoingContext function in combination.

Here’s an example:

  1. import (
  2. "context"
  3. "time"
  4. "google.golang.org/grpc"
  5. "google.golang.org/grpc/metadata"
  6. )
  7. func main() {
  8. // create a connection to the gRPC server
  9. conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
  10. if err != nil {
  11. // handle error
  12. }
  13. defer conn.Close()
  14. // create a new gRPC client with the connection
  15. client := mypb.NewMyServiceClient(conn)
  16. // set a timeout for each gRPC call
  17. ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*5)
  18. defer cancel()
  19. // add metadata to the client
  20. md := metadata.Pairs(
  21. "authorization", "Bearer mytoken",
  22. "request-id", "12345",
  23. )
  24. ctxMetadata := metadata.NewOutgoingContext(ctxTimeout, md)
  25. // make a gRPC call with the timeout and metadata
  26. resp, err := client.MyMethod(ctxMetadata, &mypb.MyRequest{})
  27. if err != nil {
  28. // handle error
  29. }
  30. // process response
  31. }

In this example, we create a new gRPC client with a connection to the server. We then set a timeout of 5 seconds for each gRPC call using context.WithTimeout. We also add metadata to the client using metadata.NewOutgoingContext, which takes the timeout context as its first argument and the metadata as its second argument.

Finally, we make a gRPC call to a hypothetical MyMethod method on the server, passing in the metadata context as well as a request message. If there is an error, we handle it appropriately. If the call is successful, we process the response as needed.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=740

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?