In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
The main content of this article is to explain "what is the development method of gRPC for GO". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what is the GO version of gRPC development method"!
Environment related
The rest of the development is carried out in the $GOPATH directory, and my real directory here is / home/golang/gopath
Create a new helloworld directory under the / home/golang/gopath/src directory as the directory for the next practical use
After completing all the development of this article, the final contents of the $GOPATH/src/helloworld directory are as follows:
[golang@centos7 src] $tree helloworld/helloworld/ ├── client │ └── client.go ├── helloworld.pb.go ├── helloworld.proto └── server └── server.go2 directories, 4 files write proto file
The proto file is used to describe the information related to the remote service, such as method signature, data structure, etc. The proto file in this article is called helloworld.proto, the location is $GOPATH/src/helloworld, and the content is as follows:
/ / Protocol type syntax = "proto3"; / / Service name service Greeter {/ / specific remote service method rpc SayHello (HelloRequest) returns (HelloReply) {}} / / SayHello method input parameter, there is only one string field message HelloRequest {string name = 1 The return value of the} / / SayHello method, with only one string field message HelloReply {string message = 1;} generating go source code based on proto
From the directory where helloworld.proto is located, execute the following command:
Protoc-go_out=plugins=grpc:. Helloworld.proto
If there are no syntax errors in helloworld.proto, the file helloworld.pb.go will be generated in the current directory, which is the code automatically generated by the tool protoc-gen-go, which will be used in the development of both the server and the client.
The following is the code snippet of helloworld.pb.go, which is used to register the service. The input parameter is that GreeterServer is an interface, so it can be inferred that on the server side, the specific business code implements the GreeterServer interface and calls the RegisterGreeterServer method to register, so that the service called remotely by the client can realize the business function:
Func RegisterGreeterServer (s * grpc.Server, srv GreeterServer) {s.RegisterService (& _ Greeter_serviceDesc, srv)} type GreeterServer interface {/ / specific remote service method SayHello (context.Context, * HelloRequest) (* HelloReply, error)}
With the Structure panel of GoLand, you can take a closer look at helloworld.pb.go:
Write the server code server.go and start
Create a new folder server under the $GOPATH/src/helloworld directory and a new server.go under this folder. The contents are as follows, and detailed comments have been added:
Package mainimport ("context"log"net"google.golang.org/grpc" pb "helloworld") const (port = ": 50051") / / defines the structure, which is used as an input parameter when calling the registration api. / / the structure takes the SayHello method with the business code / / so that the business code is executed when the remote call is made, which is automatically generated in type server struct {/ / pb.go. Is an empty structure pb.UnimplementedGreeterServer} / / the business code is written here. When the client calls SayHello remotely, / / it executes the code func (s * server) SayHello (ctx context.Context, in * pb.HelloRequest) (* pb.HelloReply, error) {/ / print request parameter log.Printf ("Received:% v", in.GetName ()) / / instantiated structure HelloReply As the return value return & pb.HelloReply {Message: "Hello" + in.GetName ()}, nil} func main () {/ / the protocol and port lis to listen on, err: = net.Listen ("tcp", port) if err! = nil {log.Fatalf ("failed to listen:% v") Err)} / / instantiate the gRPC server structure s: = grpc.NewServer () / / Service Registration pb.RegisterGreeterServer (s, & server {}) log.Println ("start listening" Wait for a remote call. ") if err: = s.Serve (lis) Err! = nil {log.Fatalf ("failed to serve:% v", err)}}
Execute go run server.go in the directory where server.go is located, and the console prompt is as follows:
[golang@centos7 server] $go run server.go starts listening at 08:20:32 on 2020-12-13, waiting for a remote call.
At this point, the server of gRPC has been started and can respond to remote calls, and then the client code is developed.
Write the client code client.go and start
Open another console.
Create a new folder client under the $GOPATH/src/helloworld directory and a new client.go under this folder. The contents are as follows, and detailed comments have been added:
Package mainimport ("context"log"os"time"google.golang.org/grpc" pb "helloworld") const (address = "localhost:50051" defaultName = "world") func main () {/ / remote connection server conn, err: = grpc.Dial (address, grpc.WithInsecure () Grpc.WithBlock () if err! = nil {log.Fatalf ("did not connect:% v", err)} / / main method closes the remote connection defer conn.Close () / / instantiates the data structure c: = pb.NewGreeterClient (conn) / / request parameters for remote calls If it is not passed in from the command line Set ctx with the default value name: = defaultName if len (os.Args) > 1 {name = os.Args [1]} / / timeout, cancel: = context.WithTimeout (context.Background (), time.Second) defer cancel () / / remote call r, err: = c.SayHello (ctx & pb.HelloRequest {Name: name}) if err! = nil {log.Fatalf ("could not greet:% v", err)} / / print out the server return information log.Printf ("Greeting:% s", r.GetMessage ())}
Execute go run client.go in the directory where the client.go is located, and immediately initiate a remote call to the server. The console prompt is as follows. You can see that the return information Hello world of the server is obtained:
[golang@centos7 client] $go run client.go2020/12/13 08:38:05 Greeting: Hello world
Then go to the server console to take a look. Through the log, it is found that the business code has been executed and the parameters of the remote request have been received:
[golang@centos7 server] $go run server.go starts listening at 08:20:32 on 2020-12-13, waiting for a remote call... 2020-12-13 08:38:05 Received: world
Go back to the client console, try it with parameters on the command line, enter go run client.go abc, and receive the server response as follows:
[golang@centos7 client] $go run client.go abc2020/12/13 08:56:36 Greeting: Hello abc
Go to the server console to have a look, and successfully received the abc:
[golang@centos7 server] $go run server.go starts listening at 08:20:32 on 2020-12-13, waiting for a remote call... 2020-12-13 08:38:05 Received: world2020/12/13 08:56:36 Received: abc here, I believe you have a deeper understanding of the "GO version of gRPC development method is what" might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.