# go get -u github.com/golang/protobuf/{proto,protoc-gen-go} # go get -u google.golang.org/grpc
# git clone https://github.com/google/protobuf.git # git checkout v3.4.1 ### 下面的命令在 Developer Command Prompt for VS2012 命令行執行 # cd D:\Project\protobuf\cmake\ # mkdir build # cd build # cmake -Dprotobuf_BUILD_TESTS=OFF ..
使用VS2012打開build目錄下的protobuf.sln文件,在protoc上右鍵->生成,最終生成的protoc.exe位於build的Debug目錄下html
向PATH添加protoc.exe路徑git
剩餘步驟參考go RPC官方教程github
import ( "net" "net/rpc" "time" "math/rand" "fmt" "strconv") type Arith int func (t *Arith) Hello(arg *int, reply *string) error { wait := rand.Intn(5) time.Sleep(time.Duration(wait) * time.Second) *reply = "Answer for " + strconv.Itoa(*arg) + " (" + strconv.Itoa(wait) + " )" return nil } func main() { arith := new(Arith) rpc.Register(arith) l, e := net.Listen("tcp", "127.0.0.1:8000") if e != nil { fmt.Print("listen error:", e) } rpc.Accept(l) }
客戶端代碼golang
import ( "net/rpc" "fmt" "time" "strconv" "runtime") func asyncCall(client *rpc.Client, num int) { var reply string divCall := client.Go("Arith.Hello", &num, &reply, nil) replyCall := <-divCall.Done if replyCall.Error != nil { fmt.Printf("Call %d failed.", num) } else { fmt.Println(strconv.Itoa(num), " : ", reply) } } func main() { runtime.GOMAXPROCS(3) client, err := rpc.Dial("tcp", "127.0.0.1:8000") if err != nil { fmt.Print("arith error:", err) } defer client.Close() for i := 0; i < 100; i++ { go asyncCall(client, i) } time.Sleep(20 * time.Second) }
經過實驗發現一個Client鏈接能夠被多個goroutine同時使用,因此並不須要爲每一個遠程調用建立一個Client鏈接async