Search code examples
gorpc

How to manage rpc.Client in golang


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

Solution

  • 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