JustNote
  • Introduction
  • DesignPattern
    • 七大原则
      • 开闭原则(OCP)
      • 依赖倒置原则(DIP)
      • 单一职责原则(SRP)
      • 接口隔离原则(ISP)
      • 迪米特法则(LoD)
      • 里氏代换原则(LSP)
      • 合成复用原则(CRP)
    • 创建型模式
      • 简单工厂模式
      • 工厂方法模式
      • 抽象工厂模式
      • 建造者模式
      • 单例模式
      • 原型模式
    • 结构型模式
      • 外观模式
      • 装饰模式
      • 适配器模式
      • 享元模式
      • 组合模式
      • 桥接模式
      • 代理模式
    • 行为型模式
      • 模板方法模式
      • 迭代器模式
      • 策略模式
      • 解释器模式
      • 观察者模式
      • 备忘录模式
      • 命令模式
      • 中介者模式
      • 责任链模式
      • 访问者模式
      • 状态模式
  • Java
    • Java Core
      • JVM 如何加载类
      • JVM 垃圾回收
      • JVM G1GC
      • JVM G1GC Q&A
      • JVM 与 Hbase
      • JVM ZGC Overview
      • JVM ZGC 内存管理
      • JVM ZGC 线程
      • JVM ZGC 垃圾回收
      • JVM ZGC 日志分析
      • JVM ZGC 参数调优
    • checkstyle
  • Golang
    • 源码阅读
      • Goroutines
      • Channel
    • gRPC
      • 1、快速开始
      • 2、什么是gRPC
      • 3、gRPC概念梳理
      • 4、基于Golang的gRPC入门
      • 5、gRPC组件ProtocolBuffers介绍
      • 6、gRPC组件Http 2.0
      • 7、错误处理和Debug
      • 8、gRPC身份验证
      • 9、服务注册与发现
      • 10、gRPC与gRPC Gateway
      • 11、gRPC与分布式链路追踪
  • Scala
    • 数据结构与算法
      • 数组
      • 队列
    • 函数式编程
      • 高阶函数
      • 偏函数
    • Immutable Collection
      • List
    • Mutable Collection
      • Array
    • 常见函数操作
      • A
        • aggregate
        • andThen
        • appended
        • appendedAll
      • C
        • chain
        • collect
        • collectFirst
        • combinations
        • compose
        • concat
        • cond
        • condOpt
        • const
        • contains
        • containsSlice
        • copyToArray
        • corresponds
        • count
        • curried
      • D
        • diff
        • distinct
        • distinctBy
        • drop
        • dropRight
        • dropWhile
      • E
        • empty(PartialFunction)
        • empty(collections)
        • endsWith
        • exists
      • F
        • fill
        • filter
        • filterKeys
        • filterNot
        • find
        • findLast
        • flatMap
        • flatten
        • fold
        • foldLeft
        • foldRight
        • forall
        • foreach
        • fromFunction
      • G
        • getOrElse (Map)
        • getOrElse (Option)
        • groupBy
        • groupMap
        • groupMapReduce
        • grouped
      • H
        • head
        • headOption
      • I
        • indexOf
        • indexOfSlice
        • indexWhere
        • indices
        • init
        • inits
        • intersect
        • isDefinedAt (Map)
        • isDefinedAt (Seq)
        • isEmpty
        • isTraversableAgain
      • K
        • keys
      • L
        • last
        • lastIndexOf
        • lastIndexOfSlice
        • lastIndexWhere
        • lastOption
        • length
        • lift
      • M
        • map
        • mapConserve
        • mapValues
        • max
        • maxBy
        • maxByOption
        • maxOption
        • min
        • minBy
        • minByOption
        • minOption
        • mkString
      • N
        • nonEmpty
      • O
        • orElse
      • P
        • padTo
        • par
        • partition
        • partitionMap
        • patch
        • permutations
        • prefixLength
        • prepended
        • prependedAll
        • product
      • R
        • range
        • reduce
        • reduceLeft
        • reduceLeftOption
        • reduceOption
        • reduceRight
        • reduceRightOption
        • reverse
        • reverseIterator
        • reverseMap
        • runWith
      • S
        • sameElements
        • scan
        • scanLeft
        • scanRight
        • search
        • segmentLength
        • size
        • slice
        • sliding
        • sortBy
        • sortWith
        • sorted
        • span
        • splitAt
        • startsWith
        • sum
      • T
        • tabulate
        • tail
        • tails
        • take
        • takeRight
        • takeWhile
        • transpose
        • tupled
      • U
        • unfold
        • union
        • unlift
        • untupled
        • unzip
        • unzip3
        • updated
      • V
        • values
        • view
      • W
        • withFilter
        • withDefault
        • withDefaultValue
      • Z
        • zip
        • zipAll
        • zipWithIndex
      • map
      • flatmap
      • filter
      • reduceLeft
      • foldLeft
    • Futures
      • Method with future as return type
      • Non blocking future result
      • Chain futures using flatMap
      • Chain futures using for comprehension
      • Future Option with for comprehension
      • Future Option with map
      • Composing Futures
      • Future Sequence
      • Future Traverse
      • Future foldLeft
      • Future reduceLeft
      • Future firstCompletedOf
      • Future zip
      • Future zipWith
      • Future andThen
      • Future configure threadpool
      • Future recover
      • Future recoverWith
      • Future fallbackTo
      • Future promise
    • Akka
  • Algorithm
  • Docker
  • Kubernetes
    • 二进制安装kubernetes
      • 00.从零开始
  • Architecture
    • Infrastructure
      • Opentracing
      • Jaeger && ZipKin
      • SkyWalking
      • Consul
      • Envoy
      • Service Mesh
      • Service Mesh: Istio 详解
      • Service Mesh: 基于 Istio 的落地实践(一)
    • CAS
      • CAS Server
      • CAS Service Management
      • CAS 集成LDAP
      • CAS 集成gitlab
      • CAS SSO & SLO
      • CAS Gitbook
    • xCAT
  • Netty
  • DDD
  • Reactive Programming
    • Reactor
      • Publisher
      • Subscriber
      • Subscription
      • Processor
    • WebFlux
  • Gitlab
    • Git Hook
  • CICD
    • Jenkins
      • Kubectl
Powered by GitBook
On this page
  • 先决条件
  • Go Version
  • Install gRPC
  • Install Protocol Buffers v3
  • Download the example
  • Build the example
  • Try it
  • Update a gRPC service
  • Generate gRPC code
  • Update and run the application
  • Update the server
  • Update the client
  • Run
  • NEXT

Was this helpful?

  1. Golang
  2. gRPC

1、快速开始

PreviousgRPCNext2、什么是gRPC

Last updated 6 years ago

Was this helpful?

先决条件

Go Version

gRPC 要求go的版本是1.6或者更高

go version

Install gRPC

使用下面的命令去安装gRPC

go get -u google.golang.org/grpc

Install Protocol Buffers v3

解压到自己特定的目录,然后配置环境变量。

接下来,为Go安装protoc插件。

go get -u github.com/golang/protobuf/protoc-gen-go

这时,编译后的protoc插件会位于$GOPATH/bin目录下。可以到该目录下确认是否存在。

Download the example

前面我们下载的 gRPC go get google.golang.org/grpc,同样包含了gRPC的example,位于 $GOPATH/src/google.golang.org/grpc/examples 目录下。

Build the example

切换到 example 目录下

cd $GOPATH/src/google.golang.org/grpc/examples/helloworld

gRPC服务在 .proto 文件中定义,该文件用于生成相应的.pb.go文件。 .pb.go文件是通过使用protoc 编译器编译 .proto 文件生成的。

出于演示Demo的目的, helloworld.pb.go 文件已经被生成了 (通过编译 helloworld.proto ), 位于 $GOPATH/src/google.golang.org/grpc/examples/helloworld/helloworld.

helloworld.pb.go 文件包含两部分内容:

  • 生成client和server端的代码

  • 用于填充,序列化和检索HelloRequest和HelloReply消息类型的代码

这是example的代码目录结构。

Try it

下面我们就来真枪实弹的跑一下代码看看。

进入到 example的目录 $GOPATH/src/google.golang.org/grpc/examples/helloworld,首先运行server端代码。

go run greeter_server/main.go

然后另外开启一个终端,运行client端代码。

go run greeter_client/main.go

此时如果运行没有出现问题的话。client 端会输出 Greeting: Hello world .

Update a gRPC service

位于 helloworld/helloworld.proto 文件中。

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

接下来,我们给service 再加上一个方法。

编辑helloworld/helloworld.proto 文件,添加一个 SayHelloAgain 的方法,它与 SayHello 方法接收同样的参数,有同样的返回值。

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}

  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

Generate gRPC code

接下来,我们更新我们的gRPC代码,让我们的应用采用新的方法定义。

protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld

这个命令会让helloworld.pb.go自动生成我们刚才的改变。

Update and run the application

刚才我们已经自动生成了 server 和 client 代码。但是我们仍然需要手动编写和调用这个新的方法。

Update the server

编辑 greeter_server/main.go 文件,添加下面的这样一个方法。

func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello again " + in.Name}, nil
}

Update the client

编辑 greeter_client/main.go 在main函数中添加下面这样一段代码。

r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: name})
if err != nil {
        log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)

Run

接下来就可以运行了。开启两个终端分别运行 server和client.运行结果如下所示。

go run greeter_client/main.go
2019/06/02 19:25:56 Greeting: Hello world
2019/06/02 19:25:56 Greeting: Hello again world

NEXT

如果国内的网络环境不允许的话,可以点击 ,查看相应的解决办法。

安装用于生成gRPC服务代码的protoc编译器.最简单的版本就是从这个地址 下载预编译好的二进制包,选择对应的平台以及版本就可以了。

接下来,如果我要更新应用程序添加新的接口给客户端调用,应该怎么做呢?gRPC服务默认是使用 protocol buffers 来定义的。可以点击 和 这两篇文章来 查看如何在 .proto 文件中定义一个服务。现在我们只需要之道,服务器和客户端都有一个SayHello RPC方法,该方法从客户端获取HelloRequest参数并从服务器返回HelloReply.它的定义是下面的样子.

Go Quick Start
先决条件
Go Version
Install gRPC
Install Protocol Buffers v3
Download the example
Build the example
Try it
Update a gRPC service
Generate gRPC code
Update and run the application
Update the server
Update the client
Run
NEXT
FAQ
https://github.com/protocolbuffers/protobuf/releases
什么是 gRPC?
gRPC基础
What is gRPC
gRPC Concepts
grpc-example