自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Golang 語言 gRPC 怎么使用?

開發(fā) 后端
既然我們要介紹 gRPC 怎么在 Golang 語言中使用,那么我們必須搭建 Golang 開發(fā)環(huán)境。這部分內(nèi)容比較簡單,本文就不再贅述了,如果有讀者朋友對這塊內(nèi)容不清楚,建議閱讀 Golang 官網(wǎng)文檔。

[[423367]]

01介紹

在之前的兩篇文章中,我們已經(jīng)介紹了使用 gRPC 創(chuàng)建 RPC 應(yīng)用的前導(dǎo)知識。我們了解到 gRPC 支持多語言,本文我們介紹在 Golang 語言中怎么使用 gRPC。

02準(zhǔn)備工作

既然我們要介紹 gRPC 怎么在 Golang 語言中使用,那么我們必須搭建 Golang 開發(fā)環(huán)境。這部分內(nèi)容比較簡單,本文就不再贅述了,如果有讀者朋友對這塊內(nèi)容不清楚,建議閱讀 Golang 官網(wǎng)文檔。

此外,我們還需要安裝接口設(shè)計語言 Protocol buffer 的編譯器 protoc,我們在之前的文章「Protobuf - 更小、更快、更簡單的交互式數(shù)據(jù)語言」中也已經(jīng)介紹過 protoc 的安裝方法,本文就不再贅述了,如果有需要了解的讀者朋友,可以翻閱一下這篇文章。

最后,我們介紹一下 protoc 編譯生成 pb 文件需要使用的插件 protoc-gen-go 和 protoc-gen-go-grpc。插件安裝方式,具體如下:

執(zhí)行 go install 命令安裝插件

  1. go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26 
  2.  go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 

修改 PATH

  1. $ export PATH="$PATH:$(go env GOPATH)/bin" 

完成以上兩步之后,我們就可以使用 protoc 編譯 .proto 文件,生成 pb 文件了。

03編寫 .proto 文件和生成 pb 文件

在 Golang 語言中使用 gRPC,首先編寫 .proto 文件,然后使用 protoc 編譯 .proto 文件生成 pb 文件,最后編寫剩余的 Golang 代碼。

接口設(shè)計語言 protobuf,在之前的文章 「Golang 語言 gRPC 使用的接口設(shè)計語言 protobuf」 中也已經(jīng)介紹過了,本文不再贅述,如果有需要了解的讀者朋友,可以翻閱一下這篇文章。

示例代碼:

編寫 .proto 文件。

  1. syntax = "proto3"
  2.  
  3. option go_package = "advanced_go/lesson06/proto/greeter"
  4.  
  5. service Greeter { 
  6.   rpc SayHello (HelloRequest) returns (HelloReply) {} 
  7.  
  8. message HelloRequest { 
  9.   string name = 1; 
  10.  
  11. message HelloReply { 
  12.   string message = 1; 

使用 protoc 編譯 .proto 文件,生成 pb 文件。

  1. $ protoc --go_out=. --go_opt=paths=source_relative \ 
  2. --go-grpc_out=. --go-grpc_opt=paths=source_relative \ 
  3. proto/helloworld.proto 

04編寫服務(wù)端和客戶端 Golang 代碼

我們在之前的文章中介紹過 gRPC 是什么,接下來,我們通過示例代碼介紹在 Golang 語言中怎么使用 gRPC,本文先來介紹使用 gRPC 的編碼流程,限于篇幅,關(guān)于 gRPC 的更多使用方法,后續(xù)會新開篇文章介紹。

首先使用接口設(shè)計語言 protobuf 的編譯器 protoc、protoc-gen-go 和 protoc-gen-go-grpc 插件生成 pb 文件,我們通過查看生成的 pb 文件,可以看到 protoc 為我們自動生成結(jié)構(gòu)體、接口和方法等 Golang 代碼。

接下來,我們只需把剩余的 Golang 代碼寫完就可以了,具體實(shí)現(xiàn)如下:

服務(wù)端示例代碼:

  1. const ( 
  2.  port = ":50051" 
  3.  
  4. type server struct { 
  5.  pb.UnimplementedGreeterServer 
  6.  
  7. func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 
  8.  log.Printf("Received: %v"in.GetName()) 
  9.  return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil 
  10.  
  11. func main () { 
  12.  lis, err := net.Listen("tcp", port) 
  13.  if err != nil { 
  14.   log.Fatalf("failed to listen: %v", err) 
  15.  } 
  16.  s := grpc.NewServer() 
  17.  pb.RegisterGreeterServer(s, &server{}) 
  18.  log.Printf("server listening at %v", lis.Addr()) 
  19.  if err := s.Serve(lis); err != nil { 
  20.   log.Fatalf("failed to serve: %v", err) 
  21.  } 

閱讀上面這段代碼,我們使用 Golang 語言編寫了 SayHello 方法,該方法實(shí)際上就是 pb 文件中自動生成的 SayHello 方法的具體實(shí)現(xiàn),對應(yīng)自動生成的 pb 文件 helloworld_grpc.pb.go 中的代碼如下:

  1. // UnimplementedGreeterServer must be embedded to have forward compatible implementations. 
  2. type UnimplementedGreeterServer struct { 
  3.  
  4. func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) { 
  5.  return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented"

在 main 函數(shù)中,我們使用 grpc 調(diào)用 NewServer 函數(shù)創(chuàng)建一個服務(wù),然后使用 pb 文件中的 RegisterGreeterServer 函數(shù)注冊服務(wù),對應(yīng)自動生成的 pb 文件 helloworld_grpc.pb.go 中的代碼如下:

  1. func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { 
  2.  s.RegisterService(&Greeter_ServiceDesc, srv) 

客戶端示例代碼:

  1. const( 
  2.  address = ":50051" 
  3.  defaultName = "word" 
  4.  
  5. func main () { 
  6.  conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock()) 
  7.  if err != nil { 
  8.   log.Fatalf("did not connect: %v", err) 
  9.  } 
  10.  defer conn.Close() 
  11.  c := pb.NewGreeterClient(conn) 
  12.  
  13.  name := defaultName 
  14.  if len(os.Args) > 1 { 
  15.   name = os.Args[1] 
  16.  } 
  17.  ctx, cancel := context.WithTimeout(context.Background(), time.Second
  18.  defer cancel() 
  19.  r, err := c.SayHello(ctx, &pb.HelloRequest{Namename}) 
  20.  if err != nil { 
  21.   log.Fatalf("could not greet: %v", err) 
  22.  } 
  23.  log.Printf("Greeting: %s", r.GetMessage()) 

閱讀上面這段代碼,我們使用 pb 文件中的 NewGreeterClient 方法創(chuàng)建一個客戶端,然后就可以使用創(chuàng)建的客戶端直接調(diào)用服務(wù)端的 SayHello 方法,對應(yīng)自動生成的 pb 文件 helloworld_grpc.pb.go 中的代碼如下:

  1. type GreeterClient interface { 
  2.  SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 
  3.  
  4. type greeterClient struct { 
  5.  cc grpc.ClientConnInterface 
  6.  
  7. func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { 
  8.  return &greeterClient{cc} 
  9.  
  10. func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 
  11.  out := new(HelloReply) 
  12.  err := c.cc.Invoke(ctx, "/Greeter/SayHello"inout, opts...) 
  13.  if err != nil { 
  14.   return nil, err 
  15.  } 
  16.  return out, nil 

編寫完服務(wù)端和客戶端代碼,接下來,我們分別啟動服務(wù)端和客戶端,執(zhí)行結(jié)果如下:

  1. go run grpc_server/main.go  
  2. 2021/09/11 23:02:59 server listening at [::]:50051 
  3. 2021/09/11 23:03:23 Received: word 
  4. 2021/09/11 23:03:31 Received: frank 
  5.  
  6. go run grpc_client/main.go  
  7. 2021/09/11 23:03:23 Greeting: Hello word 
  8.  
  9. go run grpc_client/main.go frank 
  10. 2021/09/11 23:03:31 Greeting: Hello frank 

05總結(jié)

本文我們介紹在 Golang 語言中怎么使用 gRPC,為了方便讀者朋友們理解,文章通過一個簡單示例從零到一的實(shí)現(xiàn),介紹了在 Golang 語言中使用 gRPC 的編碼流程。

建議讀者朋友們閱讀完本文,動手敲一遍示例代碼,來進(jìn)一步加深理解。限于篇幅,關(guān)于 gRPC 的更多使用方法,我們后續(xù)撰文介紹。

編碼流程歸納如下:

 

  1. 搭建 Golang 開發(fā)環(huán)境。
  2. 安裝 protobuf 編譯器 protoc 和插件 protoc-gen-go、protoc-gen-go-grpc,設(shè)置環(huán)境變量。
  3. 初始化項(xiàng)目 go mod init。
  4. 編寫 protobuf,生成 pb 文件,執(zhí)行 go mod tidy 整理依賴包。
  5. 編寫剩余 Golang 代碼。

 

責(zé)任編輯:武曉燕 來源: Golang語言開發(fā)棧
相關(guān)推薦

2021-09-26 10:20:06

開發(fā)Golang代碼

2022-02-20 23:15:46

gRPCGolang語言

2021-09-01 23:29:37

Golang語言gRPC

2021-06-07 23:19:44

Golang語言 Defer

2021-07-12 05:05:59

Golang語言字段

2021-01-29 08:56:13

Golang標(biāo)準(zhǔn)庫函數(shù)

2025-01-13 06:00:00

Go語言gRPC

2021-06-09 23:36:46

Golang語言版本

2021-10-10 23:02:49

Golang語言代碼

2021-06-29 23:40:19

Golang語言并發(fā)

2021-12-13 01:24:14

語言Golang panic

2021-11-08 23:09:07

Go排序數(shù)據(jù)

2021-04-28 09:02:48

Golang語言Context

2021-12-05 23:14:24

微服務(wù)GolanggRPC

2021-07-26 11:19:43

微服務(wù)開發(fā)技術(shù)

2025-02-04 13:53:18

NixGogRPC

2021-10-31 23:01:50

語言拼接字符串

2021-11-28 23:06:30

語言編程接口

2022-01-04 23:13:57

語言PanicGolang

2022-04-29 11:52:02

API代碼HTTP
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號