golang rpc

来源:转载

rpc server端(golang版本):

package mainimport ("errors""fmt""net""net/rpc""net/rpc/jsonrpc")const (URL = "127.0.0.1:5001")type Args struct {A, B int}type Arith intfunc (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 mainimport ("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 = iargs[i].B = i}//fmt.Printf("args %v /n", args)harvester_time1 := time.Now().UnixNano()var reply interr = 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



分享给朋友:
您可能感兴趣的文章:
随机阅读: