duanli9569 2019-05-09 20:27 采纳率: 100%
浏览 753
已采纳

Golang中的GRPC连接管理

我对GRPC比较陌生,我想确定我正在正确地使用golang进行连接管理。我不想为每个请求创建一个新的连接,但我也不想在扩展时造成瓶颈。

我在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
}

然后,对于每个函数,我都使用这个连接来创建一个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

这是处理GRPC连接的一种可接受的方法吗?或者说有更好的方法吗?

十分感谢。

  • 写回答

2条回答 默认 最新

  • douqiang4501 2019-05-09 22:48
    关注

    Yes, it's fine to have single GRPC client connection per service. 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.

    However I would suggest you to avoid using global variables and init functions, especially for networking setup. 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.

    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. 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.

       // 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵