🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 概述 使用`net/rpc`实现的RPC只能使用Golang语言编写的服务端/客户端之间交互 ## 使用 ### http 方式 十万请求耗时 8.4451737s <details> <summary>server.go</summary> ``` type Args struct { N, M int } type Res struct { Cal int } func (t *Args) Multiply(args *Args, reply *Res) error { reply.Cal = args.N + args.M return nil } func main() { rpc.Register(&Args{}) rpc.HandleHTTP() listener, e := net.Listen("tcp", "localhost:1235") if e != nil { log.Fatal("Starting RPC-SERVER -listen error:", e) } go http.Serve(listener, nil) select { } } ``` </details> <br /> <details> <summary>client.go</summary> ``` func main() { now := time.Now() client, err := rpc.DialHTTP("tcp", "127.0.0.1:1235") if err != nil { log.Fatal("Error dialing:", err) } defer client.Close() for i := 0; i < 100000; i++ { httpRpc(client) } since := time.Since(now) fmt.Printf("%+v\n", since.Seconds()) //8.8119631 } func httpRpc(client *rpc.Client) { type Args struct { N, M int } type Res struct { Cal int } args := &Args{7, 8} var reply Res err := client.Call("Args.Multiply", args, &reply) if err != nil { log.Fatal("Args error", err) } //fmt.Printf("%+v\n", reply.Cal) } ``` </details> <br /> ### tcp 方式 十万请求耗时 7.6936197 <details> <summary>server.go</summary> ``` type Args struct { A, B int } type Reply struct { C int } type Arith int func (t *Arith) Multiply(args *Args, reply *Reply) error { reply.C = args.A * args.B return nil } func main() { err := rpc.Register(new(Arith)) if err != nil { panic(err) } tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234") if err != nil { panic(err) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { continue } rpc.ServeConn(conn) } } ``` </details> <br/> <details> <summary>client,go</summary> ``` func main() { now := time.Now() client, err := rpc.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("Error dialing:", err) } defer client.Close() for i := 0; i < 100000; i++ { tcpRpc(client) } since := time.Since(now) fmt.Printf("%+v\n", since.Seconds()) //7.669614 } func tcpRpc(client *rpc.Client) { type Args struct { A, B int } type Reply struct { C int } reply := &Reply{} err := client.Call("Arith.Multiply", Args{1, 2}, &reply) if err != nil { log.Fatal(err) } //fmt.Println(reply) } ``` </details> <br/>