go-rpc
Posted at 2020-06-24 golang
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
package mainimport ( "errors" "fmt" "net/http" "net/rpc")type Args struct { A,B int}type Quotient struct{ Quo, Rem int}// rpc 的结构对象type Arith int/*两数相乘函数,被调用*/func (t *Arith) Multiply(args *Args, reply *int) error{ *reply = args.A + args.B return nil}/*两数相除函数,被调用*/func (t *Arith) Divide(args *Args, quo *Quotient) error{ if args.B == 0{ return errors.New("Divide by zero") } quo.Quo = args.A / args.B quo.Rem = args.A % args.B return nil}func main() { arith := new(Arith) rpc.Register(arith) rpc.HandleHTTP() err := http.ListenAndServe(":1234",nil) if err != nil { fmt.Println(err.Error()) }}
1234567891011121314151617181920212223242526272829303132333435363738394041
package mainimport ( "fmt" "log" "net/rpc")type Args struct { A,B int}type Quotient struct { Quo,Rem int}func main() { client,err := rpc.DialHTTP("tcp","localhost:1234") if err != nil { log.Fatal("Dialing: ",err) return } args := Args{17,8} var reply int // 远程过程调用 err = client.Call("Arith.Multiply",args,&reply) if err != nil { log.Fatal("arith error :",err) return } // 输出回调信息 fmt.Printf("Arith: %d * % d = %d \n",args.A,args.B,reply) var quot Quotient err = client.Call("Arith.Divide",args,") if err != nil { log.Fatal("arith error :",err) return } fmt.Printf("Arith: %d / %d = %d remainder %d \n",args.A,args.B,quot.Quo,quot.Rem) }
使用rpc.Call()函数像调用本地函数一样,至于中间网络请求过程已经被隐藏了。
rpc.Call()
Previous post: go-file Next post: go-redis