4

Golang | gRPC学习笔记-05 | 编码实践

 2 years ago
source link: https://ijayer.github.io/post/tech/code/golang/20180910-grpc-05-practice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Golang | gRPC学习笔记-05 | 编码实践

2018-09-10 651 words 2 mins read 69 times read

学习完了理论知识,开始写点 Demo 体验一番吧! Sohoo!😋

Statement: 文章转载自 大桥下的蜗牛 => 视频笔记:gRPC 从学习到生产 - Alan Shreve

gRPC 从学习到生产

按照文档内容,实现 Demo

[zhe@zhe cache-service-demo](master)$ tree
.
|-- README.md
|-- client                  // 完成 rpc 调用
|   `-- client.go
|-- error                   // 结构化错误处理
|   `-- error.go
|-- go.mod
|-- go.sum
|-- interceptor             // Client & Server 端拦截器(中间件)
|   `-- interceptor.go
|-- main.go
|-- proto                   // rpc 消息和服务定义
|   |-- app.pb.go           // stub 存根文件
|   `-- app.proto           // protocol buffers 协议
`-- server                  // rpc 服务实现和访问控制
    |-- server.go
    `-- tap.go              

5 directories, 11 files

Generate Code

$ protoc -I . --go_out=plugins=grpc:. proto/app.proto

server 实现

  • 完成 k-v 的存放和管理

    实现 CacheServer 接口

  • 通过 netutil.LimitListener(l, 1024) & grpc.MaxConcurrentStreams(64) 两个结合起来基本控制了并发的总数

  • 上下文传递和 Metadata 数据传递

    Context: 实现超时控制:

    ctx, _ = context.WithTimeout(context.Background(), 50*time.Millisecond)

    GRPC metadata,也称为 GRPC 的 Header。就像 HTTP 头一样,可以有一些 Metadata 信息传递过来。

    // client.go 添加参数
    ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("dry-run", "0")) // 设置 Metadata(即类似:HTTP HEADER)
    
    // server.og 解析参数
    md, ok := metadata.FromIncomingContext(ctx)
  • 带有日志统计中间件

    中间件(拦截器): 只要在客户端和服务端分别注册了 Interceptor, 那么进行 RPC 调用的时候,这些中间件会先被调用,因此这个中间件可以对调用进行一层包装,然后再进行调用。

  • 服务端以流的方式发送数据

client 实现

  • 完成 gRPC 的相关业务调用
  • 带有日志统计中间件

interceptor

  • 中间件模块实现

译文勘误:

  • client.go: Server 服务运行在 5051 端口

    grpc.Dial("localhost:5053")
    
    // changed to:
    
    grpc.Dial("localhost:5051")`
    • server.go: CacheService.store:map 未初始化就分配值会导致 panic
    s.store[req.Key] = req.Val
    
    // changed to:
    
    if s.store == nil {
        s.store = make(map[string][]byte)
    }
    s.store[req.Key] = req.Val

See Also

Thanks to the authors 🙂

Author zher

LastMod 2018-09-13

License CC BY-NC-ND 4.0

Reading | Be worthy to read about career and work 杭城 | 夕阳无限好

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK