rpc(远程过程调用),可以像调用本地程序一样调用远端服务,rpc分为http方式和tcp连接方式,使用http的rpc调用如下:

首先是server端:

// rpc_server project main.go
package main

import (
    "fmt"
    "net"
    "net/http"
    "net/rpc"
)

type Watcher int

func (watcher *Watcher) GetInfo(arg int, result *int) error {
    *result = 1 + arg
    return nil
}

func main() {
    watcher := new(Watcher)
    rpc.Register(watcher)
    rpc.HandleHTTP()
    listener, err := net.Listen("tcp", ":8888")
    if err != nil {
        fmt.Println("监听失败,端口可能被占用")
    }
    fmt.Println("正在监听8888端口")
    go http.Serve(listener, nil)
}

然后是client端:

// rpc_client project main.go
package main

import (
    "fmt"
    "net/rpc"
)

func main() {
    fmt.Println("正在链接中...")
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:8888")
    if err != nil {
        fmt.Println("链接服务器失败:", err)
    }
    var reply int
    err = client.Call("Watcher.GetInfo", 1, &reply)
    if err != nil {
        fmt.Println("调用远程服务失败", err)
    }
    fmt.Println("远程服务返回结果:", reply)
}

调用结果: