Go语言实现开发一个简单的gRPC Demo
目录
- Part1先决条件
- Part2开发环境准备
- Part3实战:开发一个简单的gRPC Demo
- 1.创建user-service模块
- 2.使用protobuf idl语言定义服务接口
- 3.生成客户端和服务端代码
- 4.编写服务器
- 5.编写客户端
- Part4验证效果
Part1先决条件
获得并安装好golang(https://go.dev/doc/install)
Protocol buffer compiler(protobuf编译器), protoc version 3(protoc工具版本建议为3版本),获得并安装:https://github.com/protocolbuffers/protobuf/releases
安装protocol编译器的Go插件
goinstallgoogle.golang.org/protobuf/cmd/protoc-gen-go@v1.28 goinstallgoogle.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
Part2开发环境准备
准备go环境
wgethttps://go.dev/dl/go1.20.5.linux-amd64.tar.gz tar-zxfgo1.20.5.linux-amd64.tar.gz mvgo/usr/local/
安装protobuf编译器protoc
wgethttps://github.com/protocolbuffers/protobuf/releases/download/v23.4/protoc-23.4-linux-x86_64.zip mkdirprotoc-23.4 mvprotoc-23.4-linux-x86_64.zip cdprotoc-23.4 unzipprotoc-23.4-linux-x86_64.zip rm-rfprotoc-23.4-linux-x86_64.zip cd.. mvprotoc-23.4/usr/local/
添加相关环境变量
exportGOROOT="/usr/local/go" exportGOPATH="/home/tantianran/goCode" exportGOPROXY="https://goproxy.cn,direct" exportGO111MODULE="on" exportPATH=$PATH:$GOROOT/bin:$GOPATH:$GOPATH/bin exportPROTOC_HOME=/usr/local/protoc-23.4 exportPATH=$PATH:$PROTOC_HOME/bin
Part3实战:开发一个简单的gRPC Demo
1.创建user-service模块
tantianran@go-dev:~/goCode/src$mkdiruser-service tantianran@go-dev:~/goCode/src$cduser-service/ tantianran@go-dev:~/goCode/src/user-service$gomodinit
2.使用protobuf idl语言定义服务接口
创建service包
tantianran@go-dev:~/goCode/src/user-service$mkdirservice tantianran@go-dev:~/goCode/src/user-service$cdservice/
service/users.proto内容:
syntax = "proto3"; option go_package = "user-service/service"; // 服务和方法 service Users { rpc GetUser (UserGetRequest) returns (UserGetReply) {} } // 请求消息 message UserGetRequest { string email = 1; int32 id = 2; } // 响应消息 message User { string id = 1; string first_name = 2; string last_name = 3; int32 age = 4; } message UserGetReply { User user = 1; // 嵌套 }
3.生成客户端和服务端代码
首先安装用于编译器的go语言插件protoc-gen-go
goinstallgoogle.golang.oandroidrg/protobuf/cmd/protoc-gen-go@latest
开始生成
tantianran@go-dev:~/goCode/src/user-service/service$protoc--go_out=.--go_opt=paths=source_relative--go-grpc_out=.--go-grpc_opt=paths=source_relativeusers.proto tantianran@go-dev:~/goCode/src/user-service/service$ls-l total24 -rw-rw-r--1tantianrantantianran37Jul1110:05go.mod -rw-rw-r--1tantianrantantianran3387Jul1110:10users_grpc.pb.go -rw-rw-r--1tantianrantantianran8984Jul1110:10users.pb.go -rw-rw-r--1tantianrantantianran362Jul1110:09users.proto
4.编写服务器
创建servehttp://www.devze.comr包
tantianran@go-dev:~/goCode/src$cduser-service/ tantianran@go-dev:~/goCode/src/user-service$mkdirserver tantianran@go-dev:~/goCode/src/user-service$cdserver/
server/server.go
packagemain import( "context" "log" "net" "os" users"user-service/service"//导入之前生成的包 "google.golang.org/grpc" ) //userService类型是Users服务的服务处理程序 typeuserServicestruct{ users.UnimplementedUseRSServer//这个字段对于gRPC中的任何服务实现都是强制性的 } func(s*userService)GetUser(ctxcontext.Context,in*users.UserGetRequest)(*users.UserGetReply,error){ //打印客户端传过来的数据 log.Printf("已接收到邮件地址:%s,还有ID:%d",in.Email,in.Id) //自定义数据响应给客户端 u:=users.User{ Id:"user-782935", FirstName:"tan", LastName:"tianran", Age:30, } return&users.UserGetReply{User:&u},nil } //向gRPC服务器注册Users服务 funcregisterServices(s*grpc.Server){ users.Re编程客栈gisterUsersServer(s,&userService{}) } //启动gRPC服务器 funcstartServer(s*grpc.Server,lnet.Listener)error{ repythonturns.Serve(l) } funcmain(){ listenAddr:=os.Getenv("LISTEN_ADDR") iflen(listenAddr)==0{ listenAddr=":50051" } lis,err:=net.Listen("tcp",listenAddr) iferr!=nil{ log.Fatal(err) } s:=grpc.NewServer() registerServices(s) log.Fatal(startServer(s,lis)) }
5.编写客户端
tantianran@go-dev:~/goCode/src$cduser-service/ tantianran@go-dev:~/goCode/src/user-service$mkdirclient/ tantianran@go-dev:~/goCode/src/user-service$cdclient/
client/main.go
packagemain import( "context" "log" "os" users"user-service/service"//导入之前生成的包 "google.golang.org/grpc" ) //建立与服务器的连接(通道) funcsetupGrpcConnection(addrstring)(*grpc.ClientConn,error){ returngrpc.DialContext( context.Background(), addr, grpc.WithInsecure(), grpc.Withblock(), ) } //创建客户端与Users服务通信 funcgetUserServiceClient(conn*grpc.ClientConn)users.UsersClient{ returnusers.NewUsersClient(conn) } //调用Users服务中的GetUser()方法 funcgetUser(clientusers.UsersClient,u*users.UserGetRequest)(*users.UserGetReply,error){ returnclient.GetUser(context.Background(),u) } funcmain(){ iflen(os.Args)!=2{ log.Fatal("缺少gRPC服务器地址") } conn,err:=setupGrpcConnection(os.Args[1]) iferr!=nil{ log.Fatal(err) } deferconn.Close() c:=getUserServiceClient(conn) result,err:=getUser(c,&users.UserGetRequest{ Email:"tantianran@qq.com", Id:801896, }) iferr!=nil{ log.Fatal(err) } //打印响应 log.Printf("收到响应:%s%s%s%d\n",result.User.Id,result.User.FirstName,result.User.LastName,result.User.Age) }
Part4验证效果
服务器
tantianran@go-dev:~/goCode/sandroidrc/user-service/server$ go run server.go
2023/07/12 00:59:01 已接收到邮件地址: tantianran@qq.com, 还有ID: 801896
客户端
tantianran@go-dev:~/goCode/src/user-service/client$ go run main.go localhost:50051
2023/07/12 00:59:01 收到响应: user-782935 tan tianran 30
以上就是Go语言实现开发一个简单的gRPC Demo的详细内容,更多关于Go gRPC的资料请关注编程客栈(www.devze.com)其它相关文章!
精彩评论