rpc包提供了通過網路或其他I/O串連對一個對象的匯出方法的訪問。服務端註冊一個對象,使它作為一個服務被暴露,服務的名字是該對象的類型名。註冊之後,對象的匯出方法就可以被遠端存取。服務端可以註冊多個不同類型的對象(服務),但註冊具有相同類型的多個對象是錯誤的。
服務端代碼範例:
package rpcimport ("net""net/rpc""net/rpc/jsonrpc""time""AgentManage/config""github.com/astaxie/beego/logs")func Start() {addr := config.AppConfig.RpcAddrserver := rpc.NewServer()server.Register(new(Hbs))l, e := net.Listen("tcp", addr)if e != nil {logs.Error("rpc listen error:", e)} else {logs.Info("rpc listening", addr)}defer l.Close()for {conn, err := l.Accept()if err != nil {logs.Error("rpc listener accept fail:", err)time.Sleep(time.Duration(100) * time.Millisecond)continue}go server.ServeCodec(jsonrpc.NewServerCodec(conn))}}
package rpcimport ("github.com/astaxie/beego/logs""AgentManage/models""fmt""time")type HbsRequest struct {Hostname string `json:"hostname"`Version string `json:"version"`BuildTime string `json:"build_time"`}type HbsReply struct {Status int `json:"status"`Message string `json:"message"`Data interface{} `json:"data"`}type Hbs struct{}func (t *Hbs) HealthCheck(req HbsRequest, reply *HbsReply) error {err := models.HeartbeatCreateOrUpdate(req.Hostname, req.Version, req.BuildTime)if err != nil {logs.Error("rpc error:", req.Hostname, err)*reply = HbsReply{Status: -1,Message: fmt.Sprint(err),}}*reply = HbsReply{Message: "success",}return nil}
用戶端代碼
package mainimport ("log""net/rpc/jsonrpc""fmt""time""net")type HbsRequest struct {Hostname string `json:"hostname"`Version string `json:"version"`BuildTime string `json:"build_time"`}type HbsReply struct {Status int `json:"status"`Message string `json:"message"`Data interface{} `json:"data"`}func main() {// Synchronous callfor {//client, err := jsonrpc.Dial("tcp", "192.168.1.93:36870")client, err := net.DialTimeout("tcp", "192.168.1.93:36870", 3 * time.Second)if err != nil {log.Fatal("net.DialTimeout error:", err)}clientRpc := jsonrpc.NewClient(client)args := &HbsRequest{"shhnwangjian1", "1.2", "2018-05-25 09:12:44"}reply := HbsReply{}err = clientRpc.Call("Hbs.HealthCheck", args, &reply)if err != nil {log.Fatal("clientRpc.Call error:", err)}fmt.Println(reply)client.Close()time.Sleep(10 * time.Second)}}