zoukankan      html  css  js  c++  java
  • 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:Projectprotobufcmake
    # 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连接

  • 相关阅读:
    Azure WAF防火墙工作原理分析和配置向导
    多云时代,海外微软Azure云与国内阿里云专线打通性能测试
    【Hololens】微软Hololens虚拟现实视频集
    【Azure】Azure学习方法和学习资料
    LINUX ON AZURE 安全建议(全)
    编程行业之网络贩卖生存
    Bootstrap
    我谷首开博客
    Noip2018普及组初赛试题解题报告
    奇yin技巧
  • 原文地址:https://www.cnblogs.com/silvermagic/p/9087904.html
Copyright © 2011-2022 走看看