简体   繁体   English

Golang中的GRPC连接管理

[英]GRPC Connection Management in Golang

I am relatively new to GRPC and want to be sure that I am doing connection management correctly with golang. 我对GRPC比较陌生,并希望确保我正在使用golang进行正确的连接管理。 I don't want to have to create a new connection for every call but I also don't want to create bottlenecks as I scale. 我不想为每个呼叫创建一个新连接,但我也不想在扩展时创建瓶颈。

What I did was to create a single connection in the init function: 我所做的是在init函数中创建一个连接:

var userConn *grpc.ClientConn
var userServiceName string

func init() {
    userServiceName := os.Getenv("USER_SERVICE_URL")
    if userServiceName == "" {
        userServiceName = "localhost"
    }
    logging.LogDebug("userClient:  Connecting to: "+userServiceName, "")
    tempConn, err := grpc.Dial(userServiceName, grpc.WithInsecure())
    if err != nil {
        logging.LogEmergency("account_user_client.Init()  Could not get the connection.  "+err.Error(), "")
        return
    }
    userConn = tempConn
}

And then for each function I will use that connection to create a Client: 然后对于每个函数,我将使用该连接来创建客户端:

c := user.NewUserClient(userConn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.GetUserFromTokenID(ctx, &user.GetUserFromTokenRequest{TransactionID: transactionID, OathToken: *oathToken})
//Handle Error and Response

is this an acceptable way to handle grpc connections? 这是处理grpc连接的可接受方式吗? Any recommendations on better ways? 关于更好方法的任何建议?

Thank you very much. 非常感谢你。

Yes, it's fine to have single GRPC client connection per service. 是的,每个服务都有单个GRPC客户端连接。 Moreover, I don't see any other options here. 此外,我在这里看不到任何其他选择。 GRPC does all the heavy lifting under the hood: for example, you don't need to write your own client connection pool (as you would do for a typical RDBMS), because it won't provide better results than a single GRPC connection. GRPC完成了所有繁重的工作:例如,您不需要编写自己的客户端连接池(就像您对典型的RDBMS所做的那样),因为它不会提供比单个GRPC连接更好的结果。

However I would suggest you to avoid using global variables and init functions, especially for networking setup. 但是我建议你避免使用全局变量和init函数,特别是对于网络设置。 Also you don't need to create GRPC client ( c := user.NewUserClient(userConn) ) every time you post a request to the GRPC service: this is just an extra work for garbage collector, you can create the only instance of client at the time of application startup. 每次向GRPC服务发送请求时,您也不需要创建GRPC客户端( c := user.NewUserClient(userConn) ):这只是垃圾收集器的额外工作,您可以创建唯一的客户端实例在应用程序启动时。

Update 更新

Assuming that you're writing server application (because it can be seen from the method you call on the remote GRPC service), you can simply define a type that will contain all the objects that have the same lifetime as the whole application itself. 假设您正在编写服务器应用程序(因为可以从您在远程GRPC服务上调用的方法中看到它),您可以简单地定义一个类型,该类型将包含与整个应用程序本身具有相同生命周期的所有对象。 According to the tradition, these types are usually called "server context", though it's a little bit confusing because Go has very important concept of context in its standard library. 根据传统,这些类型通常被称为“服务器上下文”,虽然它有点令人困惑,因为Go在其标准库中具有非常重要的context概念。

   // this type contains state of the server
   type serverContext struct {
       // client to GRPC service
       userClient user.UserClient

       // default timeout
       timeout time.Duration

       // some other useful objects, like config 
       // or logger (to replace global logging)
       // (...)       
   }

   // constructor for server context
   func newServerContext(endpoint string) (*serverContext, error) {
       userConn, err := grpc.Dial(endpoint, grpc.WithInsecure())
       if err != nil {
           return nil, err
       }
       ctx := &serverContext{
          userClient: user.NewUserClient(userConn),
          timeout: time.Second,
       }
       return ctx, nil
   }

   type server struct {
       context *serverContext
   }

   func (s *server) Handler(ctx context.Context, request *Request) (*Response, error) {
       clientCtx, cancel := context.WithTimeout(ctx, time.Second)
       defer cancel()
       response, err := c.GetUserFromTokenID(
          clientCtx, 
          &user.GetUserFromTokenRequest{
              TransactionID: transactionID,
              OathToken: *oathToken,
          },
       )
       if err != nil {
            return nil, err
       }
       // ...
   }

   func main() {
       serverCtx, err := newServerContext(os.Getenv("USER_SERVICE_URL"))
       if err != nil {
          log.Fatal(err)
       }
       s := &server{serverCtx}

       // listen and serve etc...
   }

Details may change depending on what you're actually working on, but I just wanted to show that it's much more better to encapsulate state of your application in an instance of distinct type instead of infecting global namespace. 细节可能会根据您实际工作的内容而改变,但我只想表明,将应用程序的状态封装在不同类型的实例中而不是感染全局命名空间会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM