gRPC入门

xxfaxy · · 609 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

目录结构

└── study
    └── rpc
        ├── c.go(客户端)
        ├── lib
        │   ├── test.pb.go(这个文件是protoc生成的)
        │   └── test.proto
        └── s.go(服务端)

test.proto

syntax = "proto3";
package lib;

service Test {
  rpc Say (Request) returns (Response) {}
}

message Request {
  string name = 1;
}

message Response {
  string age = 1;
}

编译

在rpc目录下执行

protoc -I lib lib/test.proto --go_out=plugins=grpc:lib

服务端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "net"
    "study/rpc/lib"
)

type server struct {
    lib.UnimplementedTestServer
}

func (s *server) Say(ctx context.Context, in *lib.Request) (*lib.Response, error) {
    fmt.Println(in.GetName())
    return &lib.Response{Age: in.GetName()}, nil
}

func main() {
    l, _ := net.Listen("tcp", ":10000")
    s := grpc.NewServer()
    lib.RegisterTestServer(s, &server{})
    s.Serve(l)
}

客户端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "time"
    "study/rpc/lib"
)

func main() {
    conn, _ := grpc.Dial(":10000", grpc.WithInsecure(), grpc.WithBlock())
    defer conn.Close()
    c := lib.NewTestClient(conn)
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    r, _ := c.Say(ctx, &lib.Request{Name: "c"})
    fmt.Println(r.GetAge())
}

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:xxfaxy

查看原文:gRPC入门

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

609 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传