golang--net/rpc

来源:互联网 发布:ipo 净利润 数据 编辑:程序博客网 时间:2024/06/03 17:07
用这个这个包,我们可以通过网络或者其他I/O的连接来访问其他机器上的方法。一个服务器可以注册一个对象,然后其他机器就可以用对象的类型名来远程调用这个对象的方法。当然这些可以被远程调用的方法需要一些限制:

-the method’s type is exported.
- the method is exported.
- the method has two arguments, both exported (or builtin) types.
- the method’s second argument is a pointer.
- the method has return type error.

直接上可以跑的代码:
首先是服务端,也就是提供被调用方法的一方:

package mainimport (    "errors"    "log"    "net"    "net/http"    "net/rpc")type Args struct {    A, B int}type Quotient struct {    Quo, Rem int}type Arith intfunc (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()    l, e := net.Listen("tcp", ":1234")    if e != nil {        log.Fatal("listen error:", e)    }    http.Serve(l, nil)}

然后是调用方:

package mainimport ("net/rpc""log""fmt")type Args struct {    A, B int}type Quotient struct {    Quo, Rem int}func main()  {    client, err := rpc.DialHTTP("tcp", "127.0.0.1:1234")    if err != nil {        log.Fatal("dialing:", err)    }    // Synchronous call    args := &Args{7,8}    var reply int    err = client.Call("Arith.Multiply", args, &reply)    if err != nil {        log.Fatal("arith error:", err)    }    fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)    // Asynchronous call    quotient := new(Quotient)    divCall := client.Go("Arith.Divide", args, quotient, nil)    replyCall := <-divCall.Done // will be equal to divCall    if replyCall.Error != nil {        log.Fatal("arith error:", replyCall.Error)    }    fmt.Printf("Arith: %d/%d=%d...%d", args.A, args.B, quotient.Quo, quotient.Rem)    // check errors, print, etc.}

只需要在终端先把服务端启动,然后再启动clinet.go就可以看见server.go里的服务被调用了。