在go中玩下gRPC

        gRPC很常见, 也很常用, 来玩下。

        先安装该安装的, 比如protoc, protoc-gen-go, grpc, 该设置的环境变量设置一下,这些很简单, 不必多说。

 

        写协议文件data.proto:

syntax = "proto3";
package example;

service TaogeApi {
    rpc MyFun(ReqBody) returns (RspBody){}
}

message ReqBody {
	int32  cmd = 1;
    string str = 2;
}

message RspBody {
	int32  cmd  = 1;
	int32  code = 2;
    string str  = 3;
}

         写服务端代码s.go

package main
import (
    "example"
    "net"
    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
    "golang.org/x/net/context"
    "log"
)

const (
    HOST string = "localhost"
    PORT string = "8080"
)

type Haha struct{}
func (fd *Haha) MyFun(ctx context.Context, in *example.ReqBody) (out *example.RspBody, err error) {
    log.Println("Cmd is ", in.Cmd)
    log.Println("Str is ", in.Str)

    out = &example.RspBody{Cmd:in.Cmd, Code:10086, Str:"heheda"}
    return out, nil
}

func main() {
    listener, err := net.Listen("tcp", HOST + ":" + PORT)
    if err != nil {
        log.Fatalln("failed to listen at: " + HOST + ":" + PORT)
    } else {
        log.Println("server is listening at: " + HOST + ":" + PORT)
    }

    rpcServer := grpc.NewServer()
    example.RegisterTaogeApiServer(rpcServer, &Haha{})
    reflection.Register(rpcServer)

    if err = rpcServer.Serve(listener); err != nil {
        log.Fatalln("failed to serve at: " + HOST + ":" + PORT)
    }
}

        让服务端跑起来。

        写客户端代码c.go:

package main
import (
    "google.golang.org/grpc"
    "log"
    "example"
    "golang.org/x/net/context"
)

const (
    ADDRESS string = "localhost:8080"
)

func main() {
    conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
    if err != nil {
        log.Fatalln("failed to connect: " + ADDRESS)
    }
    defer conn.Close()

    client := example.NewTaogeApiClient(conn)
    rsp,err := client.MyFun(context.Background(), &example.ReqBody{Cmd:110, Str:"hehe"})
    if err != nil {
        log.Fatalln("MyFun error:" + err.Error())
    }

    log.Println("Cmd is ", rsp.Cmd)
    log.Println("Code is ", rsp.Code)
    log.Println("Str is ", rsp.Str)
}

         也跑起来。

 

         客户端log为:

2018/09/21 22:12:17 Cmd is  110
2018/09/21 22:12:17 Code is  10086
2018/09/21 22:12:17 Str is  heheda

         

       有个地方要注意, 在data.proto文件中,变量是小写的, 但protoc和protoc-gen-go转换成为大写的(联想go的特性,想想为什么?),而且连下划线也转啊,有兴趣的可以试试。 我之前也说过一次(那一次是把大写转化为小写的了)。

      不多说。

 

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值