当前位置:网站首页>云原生应用开发之 gRPC 入门
云原生应用开发之 gRPC 入门
2022-07-07 23:48:00 【InfoQ】
什么是 gRPC

特点
- gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。
- 在 gRPC 里客户端应用可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用和服务。
- gRPC 默认使用 protocol buffers,这是 Google 开源的一套成熟的结构数据序列化机制,它的作用与 XML、json 类似,但它是二进制格式,性能好、效率高(缺点:可读性差)。
gRPC 和 REST 区别
- gRPC 使用 HTTP/2 协议,而 REST 使用 HTTP 1.1
- gRPC 使用协议缓冲区数据格式,而不是通常在 REST API 中使用的标准 JSON 数据格式
- 使用 gRPC,您可以根据需要利用 HTTP/2 功能,例如服务器端流式传输、客户端流式传输甚至双向流式传输。
Go 建立一个 gRPC 服务器
- 安装 golang 的proto工具包:
go get -u github.com/golang/protobuf/proto
- 在开始建立 gRPC 之前,确保已安装 Protocol Buffers v3:
go get -u github.com/golang/protobuf/protoc-gen-go
- 在 Go 中安装 gRPC:
go get google.golang.org/grpc
main
package main
import (
"log"
"net"
)
func main() {
lis, err := net.Listen("tcp", ":8000")
if err != nil {
log.Fatalf("Fail to listen: %v", err)
}
}
package main
import (
"log"
"net"
"google.golang.org/grpc"
)
func main() {
lis, err := net.Listen("tcp", ":8000")
if err != nil {
log.Fatalf("Fail to listen: %v", err)
}
grpcServer := grpc.NewServer()
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("Fail to serve: %v", err)
}
}
添加一些功能
client.proto
syntax = "proto3"; // 协议为proto3
package chat;
// 定义发送请求信息
message Message {
// 定义发送的参数
// 参数类型 参数名 标识号(不可重复)
string body = 1;
}
// 定义我们的服务(可定义多个服务,每个服务可定义多个接口)
service ChatService {
rpc SayHello(Message) returns (Message) {}
}
.proto
ChatService
SayHello
.proto
$ protoc --go_out=plugins=grpc:chat chat.proto
chat/chat.pb.go
server.go
package main
import (
"fmt"
"log"
"net"
"github.com/tutorialedge/go-grpc-beginners-tutorial/chat"
"google.golang.org/grpc"
)
func main() {
fmt.Println("Go gRPC Beginners Tutorial!")
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 9000))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := chat.Server{}
grpcServer := grpc.NewServer()
chat.RegisterChatServiceServer(grpcServer, &s)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
package chat
import (
"log"
"golang.org/x/net/context"
)
type Server struct {
}
func (s *Server) SayHello(ctx context.Context, in *Message) (*Message, error) {
log.Printf("Receive message body from client: %s", in.Body)
return &Message{Body: "Hello From the Server!"}, nil
}
chat.proto
$ go run server.go
Go gRPC Beginners Tutorial!
localhost:8000
在 Go 中构建 gRPC 客户端
client.go
package main
import (
"log"
"golang.org/x/net/context"
"google.golang.org/grpc"
"github.com/tutorialedge/go-grpc-beginners-tutorial/chat"
)
func main() {
var conn *grpc.ClientConn
conn, err := grpc.Dial(":8000", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %s", err)
}
defer conn.Close()
c := chat.NewChatServiceClient(conn)
response, err := c.SayHello(context.Background(), &chat.Message{Body: "Hello From Client!"})
if err != nil {
log.Fatalf("Error when calling SayHello: %s", err)
}
log.Printf("Response from server: %s", response.Body)
}
$ go run client.go
2022/07/07 23:23:01 Response from server: Hello From the Server!
安装问题
go get google.golang.org/grpc

- git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
- git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net
- git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
- go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
- git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
- cd $GOPATH/src/
- go install google.golang.org/grpc
总结
- Go gRPC Beginners Tutorial
- 《gRPC 与云原生应用开发》
边栏推荐
- Use "recombined netlist" to automatically activate eco "APR netlist"
- 2022 high altitude installation, maintenance and demolition examination materials and high altitude installation, maintenance and demolition operation certificate examination
- QT build with built-in application framework -- Hello World -- use min GW 32bit
- 2021 Shanghai safety officer C certificate examination registration and analysis of Shanghai safety officer C certificate search
- 如果时间是条河
- Micro rabbit gets a field of API interface JSON
- 5. Contrôle discret et contrôle continu
- About snake equation (5)
- 滑环在直驱电机转子的应用领域
- A little experience from reading "civilization, modernization, value investment and China"
猜你喜欢
Content of one frame
2022 high voltage electrician examination skills and high voltage electrician reexamination examination
Understanding of maximum likelihood estimation
Application of state mode in JSF source code
2021-03-06 - play with the application of reflection in the framework
Leetcode exercise - Sword finger offer 36 Binary search tree and bidirectional linked list
qt--將程序打包--不要安裝qt-可以直接運行
About how USRP sets the sampling frequency below the minimum sampling frequency reached by the hardware
Basic realization of line graph
2022 new examination questions for crane driver (limited to bridge crane) and question bank for crane driver (limited to bridge crane) operation examination
随机推荐
COMSOL - Construction of micro resistance beam model - final temperature distribution and deformation - establishment of geometric model
用户之声 | 冬去春来,静待花开 ——浅谈GBase 8a学习感悟
NPM Internal Split module
2022 safety officer-c certificate examination summary and safety officer-c certificate reexamination examination
Led serial communication
npm 内部拆分模块
Qt - - Packaging Programs - - Don't install Qt - can run directly
2022 safety officer-b certificate examination question bank and safety officer-b certificate simulation test questions
QT--创建QT程序
Content of one frame
General configuration toolbox
Four digit nixie tube display multi digit timing
break net
解决报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
Anaconda3 download address Tsinghua University open source software mirror station
The beauty of Mathematics -- the principle of fine Fourier transform
Understanding of prior probability, posterior probability and Bayesian formula
qt--將程序打包--不要安裝qt-可以直接運行
Gnuradio 3.9 using OOT custom module problem record
用户之声 | 对于GBase 8a数据库学习的感悟