Welcome to my GitHub

Github.com/zq2599/blog…

Content: All original articles and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.

GRPC Learning series links

  1. Deploy and set up GO in CentOS7
  2. GRPC development environment preparation for GO
  3. Preliminary GO version gRPC development
  4. Four types of service methods
  5. GRPC – Gateway of actual combat
  6. GRPC – Gateway integration swagger

This paper gives an overview of

  • This article “gRPC learning” series of the fifth, gRPC is often used for mutual invocation between the server, if you want to expose the service to the front end, although hands-on modification of the server can also be achieved, but it seems to increase a lot of work, at this time you can also choose gRPC-Gateway way to quickly expose the gRPC service in the HTTP way;
  • Grpc-gateway works as shown in the following figure. With the help of the GRPC-Gateway plug-in, the code of the Reverse Proxy can be generated based on the Proto file. After running, the Reverse Proxy can provide external RESTful services. After receiving a RESTful request, invoke the original gRPC service through gRPC:

  • This paper shows the whole process of grPC-Gateway environment construction, development, and verification, which consists of the following steps:
  1. Fast building grPC-Gateway environment;
  2. Write proto files;
  3. According to the PROto file gRPC, GRPC-gateway source code;
  4. Add business code;
  5. Compile, run, verify;

Specify files and directories in advance

  • $GOPATH/ SRC = $GOPATH/ SRC = $GOPATH/ SRC
[golang@centos7 SRC]$tree │ ├── gateway │ ├─ ├─.gw. Go ├── helloworld.pb.go ├─ Go ├── Helloworld.pb.gw. Go ├── Helloworld.proto ├── helloworld.swagger. Json ├─ server ├─ server.goCopy the code
  • The preparation work is finished, then the development begins formally;

The premise condition

  • All operations in this article do not use the root account, but the Golang account created earlier;
  • Please refer to the following two articles to build the GO environment and gRPC environment:
  1. Deploy and set up GO in CentOS7
  2. GRPC development environment preparation for GO

Build the GRPC-Gateway environment as quickly as possible

  • Building a GRPC-Gateway environment actually does three things:

  1. When building the environment, I referred to some articles on the Internet, but failed to meet various problems. (OF course, I don’t think there is a problem with the article, and I must realize that it is caused by my lack of ability.)
  2. After a lot of twisting and turning, I turned everything into a shell script and executed the following command to do everything shown above:
curl -o install-grpc-gateway.sh \
https://raw.githubusercontent.com/zq2599/blog_demos/master/files/install-grpc-gateway.sh \
&& chmod a+x ./install-grpc-gateway.sh \
&& ./install-grpc-gateway.sh
Copy the code
  1. $GOPATH/bin = $GOPATH/bin = $GOPATH/bin = $GOPATH/bin = $GOPATH/bin = $GOPATH/bin
[golang@centos7 ~]$CD $GOPATH/bin [golang@centos7 bin]$ls-al Drwxrwxr-x. 5 Golang Golang 39 12月 19 08:21.. -rwxr-x--. 1 Golang golang 5253272 12月 19 08:20 protoc-rwxr-x. 1 Golang golang 8461147 12月 19 08:21 protoc-gen-go -rwxrwxr-x. 1 Golang golang 6717463 December 19 08:59 Protoc-gen-grPC-gateway-rwxrwxr-x. 1 Golang golang 6908535 December 19 08:59 protoc-gen-swaggerCopy the code
  • Now that the environment is ready, start developing;

Write the proto file

  • In the $GOPATH/ SRC directory, create a new folder called helloworld and create a new file called helloworld.proto.
// Protocol type
syntax = "proto3";

/ / package name
package helloworld;

import "google/api/annotations.proto";

// The name of the service defined
service Greeter {
  // The specific remote service method
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      post: "/helloworld"
      body: "*"}; }}// The input to the SayHello method is a string field
message HelloRequest {
  string name = 1;
}

// The return value of the SayHello method has only one string field
message HelloReply {
  string message = 1;
}
Copy the code
  • The above proto file has the following points to note:
  1. The whole file is actually based on the helloWorld. Proto in the “preliminary GO version gRPC Development” article, adding two parts of the content;
  2. Increase in the first place, it is to use the import keywords into Google/API/annotations. The proto.
  3. The second option configuration is added to the statement of SayHello. The option configuration is used to configure information about the RESTful interface exposed by SayHello.
  4. When using protoc-gen-GrPC-Gateway, these two configurations are recognized and the corresponding code is generated.

Generate gRPC, gRPC-Gateway source code according to proto file

  1. Proto file is written, the next is to generate gRPC, GRPC-gateway source;
  2. The command to generate gRPC source code has been used in the previous article, as follows:
protoc -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--go_out=plugins=grpc:. \
helloworld.proto
Copy the code
  1. After the execution, the helloWorld.pb. go file is generated in the current directory.
  2. Run the following command to generate grPC-gateway source code:
protoc -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--grpc-gateway_out=logtostderr=true:. \
helloworld.proto
Copy the code
  1. After the execution, the helloWorld.pb.gw. go file is generated in the current directory.
  2. Execute the command that generates the Swagger file:
protoc -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--swagger_out=logtostderr=true:. \
helloworld.proto
Copy the code
  1. When done, the helloWorld.swagger. json file is generated in the current directory;
  2. So far, the helloWorld directory contains these contents:
[golang@centos7 SRC]$tree │ ├─ ├─.pb.go ├── helloworld.pb.gw. Go ├── helloworld.proto ├─  helloworld.swagger.json 0 directories, 4 filesCopy the code
  1. Next, start coding to complete the code needed to run the entire service.
  2. Due to space constraints, this article will not cover swagger-related development and validation, so the generated helloWorld.swagger. json file will not be used in this article and will be used in the next article.

Write the server code server.go and start it

  1. Next, write server code server.go, this and “preliminary go version gRPC development” in the server. Go content is the same;
  2. $GOPATH/ SRC/helloWorld = $GOPATH/ SRC/helloWorld = $GOPATH/ SRC/helloWorld = $GOPATH/ SRC/helloWorld
package main import ( "context" "log" "net" "google.golang.org/grpc" pb "helloworld" ) const ( port = ":50051" ) // Type server struct {// pb.go (struct) {// struct (struct) {// pb.go (struct); The structure pb is empty. UnimplementedGreeterServer} / / business code in this writing, the client remote call SayHello, Func (s *server) SayHello(CTX context. context, in * pb.helloRequest) (* pb.helloReply, Error) {// Print the request parameter log.printf ("Received: %v", in.getName ()) // instantiate the structure HelloReply as a return value return & pb.helloReply {Message: "Hello "+ in.getName ()}, nil} func main() {// protocol and port to Listen to lis, err := net.listen (" TCP ", port) if err! = nil { log.Fatalf("failed to listen: %v", err)} // instantiate gRPC server structure s := grpc.newServer () // register pb.registergreeterServer (s, &server{}) log.println (" start listening, Waiting for a remote call..." ) if err := s.Serve(lis); err ! = nil { log.Fatalf("failed to serve: %v", err) } }Copy the code
  1. Run go run server.go in the server.go directory. The following message is displayed on the console:
[golang@centos7 server]$go run server.go 2020/12/13 08:20:32Copy the code
  1. At this point, the gRPC server has been started and can respond to remote calls. Next, the Reverse Proxy is developed.

Write the Reverse Proxy code helloWorld.gw. go and start it

  • Next, the Reverse Proxy code helloWorld.gw. go;
  • Create a new folder in $GOPATH/ SRC/helloWorld: gateway; create a new folder in this folder: helloworld.gw.go;
package main import ( "flag" "fmt" "net/http" gw "helloworld" "github.com/grpc-ecosystem/grpc-gateway/runtime" "golang.org/x/net/context" "google.golang.org/grpc" ) var ( echoEndpoint = flag.String("echo_endpoint", "localhost:50051", "endpoint of YourService") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterGreeterHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) if err ! = nil { return err } return http.ListenAndServe(":9090", mux) } func main() { if err := run(); err ! = nil { fmt.Print(err.Error()) } }Copy the code
  1. ListenAndServe listens to port 9090, which is the port that provides external RESTful services.
  2. The second thing to note is that echoEndpoint is configured to forward external RESTful requests to the entry point where server.go provides gRPC services.
  3. Attention should be paid to the third place, the RegisterGreeterHandlerFromEndpoint method is invoked the automatically generated code complete upstream and downstream call binding;
  • Go run hellowworld.gw.go in the directory where hellowworld.gW. go is located to listen for web requests on port 9090.

validation

  1. Use curl to send a request:
Curl POST \ \ - X - d '{" name ":" will "}' \ 192.168.133.203:9090 / helloworldCopy the code
  1. The following response is received, which is the content from server.go. It can be seen that the HTTP request reaches the real gRPC service provider through the Reserve Proxy and is returned to the caller smoothly:
{"message":"Hello will"}
Copy the code
  1. Go to the server.go log:
[golang@centos7 server]$go run server.go 2020/12/19 14:16:47 2020/12/19 14:24:35 Received: willCopy the code
  1. Postman can also be verified on other machines, and be sure to turn off the firewall on the server. The request and response are as follows, and be careful to set and observe in numerical order:

  • Here’s how to quickly expose gRPC services as RESTful services. If you’re trying to do this, hopefully this article will give you some references.

You are not alone. Xin Chen is with you all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to follow the public number: programmer Xin Chen

Wechat search “Programmer Chen”, I am Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…