How to manage rpc.Client in golang

huangapple go评论64阅读模式
英文:

How to manage rpc.Client in golang

问题

我有一个如下所示的包存储。

package store

type dbClient struct {
   client rpc.Client
}

func init() {
    // 初始化 dbClient
}

type Args struct{}
type Reply struct{
   Stories []interface{}
}

func GetStories() ([]interface{}, error) {
   args := Args{}
   var reply Reply
   err := dbClient.client.Call("Database.GetStories", &Args, &reply)
   return reply.Stories, err
}

我遇到了两个问题:

  1. store.GetStories 被多个 goroutine 并发调用,但 rpc.Client 会按顺序处理请求,所以如何结构化 dbClient 是最佳方式,以便能够处理 100 个并发请求到 store.GetStories?
  2. 每当我重新启动 rpc 服务器时,dbClient.client 就会断开连接,并且 dbClient.client.Call 会返回 rpc.ErrShutDown 错误。那么,检查连接并重新连接的最优方式是什么?我考虑使用一个轮询的 goroutine,但希望能得到更多的想法。
英文:

I have a package store as follows.

package store

type dbClient struct {
   client rpc.Client
}

func init() {
    // init dbClient
}
type Args struct{}
type Reply struct{
   Stories []interface{}
}

func GetStories() ([]interface{}, error) {
   args := Args{}
   var reply Reply
   err := dbClient.client.Call("Database.GetStories", &Args, &reply)
   return reply.Stories, err
}

There are two issues i am facing with this:

  1. store.GetStories is being called from multiple goroutines concurrently, but rpc.Client handles requests sequentially, so what is the best way to structure dbClient such that i am able to handle 100 concurrent requests to store.GetStories?
  2. Whenever I restart the rpc server dbClient.client get disconnected and dbClient.client.Call give error rpc.ErrShutDown. So, what will be most optimised way to check connection and reconnect? I have a polling goroutine in mind, looking for more ideas

答案1

得分: 1

最简单的解决方案是使用专为您的用例设计的方法:https://golang.org/pkg/net/rpc/#Client.Go

英文:

The simplest solution is to use the method which is made with your use case in mind: https://golang.org/pkg/net/rpc/#Client.Go

huangapple
  • 本文由 发表于 2021年6月30日 14:49:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/68189722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定