net/rpc
最后更新于:2022-04-02 02:49:43
[TOC]
## 概述
使用`net/rpc`实现的RPC只能使用Golang语言编写的服务端/客户端之间交互
## 使用
### http 方式
十万请求耗时 8.4451737s
### tcp 方式 十万请求耗时 7.6936197
';
server.go
``` 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 { } } ```client.go
``` 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) } ```### tcp 方式 十万请求耗时 7.6936197