• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go学习笔记(一)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

软件安装

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap