rpc server端(golang版本):
package main import ( "errors" "fmt" "net" "net/rpc" "net/rpc/jsonrpc" ) const ( URL = "127.0.0.1:5001" ) type Args struct { A, B int } type Arith int func (t *Arith) Add(args []Args, reply *int) error { for i := 0; i < len(args); i++ { *reply += args[i].A *reply += args[i].B } return nil } func main() { arith := new(Arith) rpc.Register(arith) tcpAddr, err := net.ResolveTCPAddr("tcp", URL) if err != nil { fmt.Println(err) } listener, err := net.ListenTCP("tcp", tcpAddr) for { conn, err := listener.Accept() if err != nil { continue } go jsonrpc.ServeConn(conn) } }
rpc client端(golang版本)
package main import ( "fmt" _ "net/rpc" "net/rpc/jsonrpc" "time" ) type Args struct { A, B int } const ( URL = "127.0.0.1:5001" ) func main() { client, err := jsonrpc.Dial("tcp", URL) defer client.Close() if err != nil { fmt.Println(err) } var args [100000]Args //批量参数 for i := 0; i < len(args); i++ { args[i].A = i args[i].B = i } //fmt.Printf("args %v \n", args) harvester_time1 := time.Now().UnixNano() var reply int err = client.Call("Arith.Add", args, &reply) //批量执行 if err != nil { fmt.Println(err) } harvester_time2 := time.Now().UnixNano() fmt.Printf("cal time %f \n", float64(harvester_time2-harvester_time1)/float64(1000000000)) fmt.Println(reply) }
执行结果: go version: go 1.4
cal time 0.185011
9999900000
有疑问加站长微信联系(非本文作者)