Go学习笔记(一)

软件安装

# go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
# go get -u google.golang.org/grpc

生成protoc

# 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目录下

向PATH添加protoc.exe路径

剩余步骤参考go RPC官方教程

原生net/rpc

服务端代码

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)
}

客户端代码

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连接

posted @ 2018-05-25 12:17  银魔术师  阅读(301)  评论(0编辑  收藏  举报