Welcome to my GitHub

Github.com/zq2599/blog…

Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

Welcome to my GitHub

Here classification and summary of xinchen all original (including supporting source code) : github.com/zq2599/blog…

GRPC learning series of articles links

  1. Deploy and set GO on CentOS7
  2. Prepare gRPC development environment for GO
  3. The first GO version of gRPC development
  4. Actual combat four kinds 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 third, the previous article has been ready to gRPC development environment, today to develop a server application and remote gRPC call it client;
  • The content and steps of today’s actual combat are as follows:

Download the source code

  • The source code for this article can be downloaded on GitHub, with the address and link information shown in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git repository address (HTTPS) Github.com/zq2599/blog… The project source warehouse address, HTTPS protocol
Git repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  • The Git project has multiple folders. The application for this chapter is in the Go-source folder, as shown in the red box below:

  • There are several sub-folders in go-Source. The source code of this piece is in HelloWorld, as shown in the red box below:

Environment related

  • The rest of the development will be done in the $GOPATH directory, which is actually /home/golang/gopath;
  • Create a helloWorld directory under /home/golang/gopath/ SRC.
  • After completing all the development for this article, the final $GOPATH/ SRC/helloWorld directory will look like this:
[golang@centos7 SRC]$├─ ├─ ├─ helloWorld.pb.go ├─ helloWorld.proto └── imp. Go exdirectories, 4 filesCopy the code

Write proto files

  • Proto: $GOPATH/ SRC/helloWorld: $GOPATH/ SRC/helloWorld
// Protocol type
syntax = "proto3";

/ / package name
package helloworld;

// The defined service name
service Greeter {
  // The specific remote service method
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

SayHello is an input parameter to the SayHello method with only one string field
message HelloRequest {
  string name = 1;
}

The SayHello method returns a single string field
message HelloReply {
  string message = 1;
}
Copy the code

Generate go source code according to Proto

  1. In the directory where helloworld.proto resides, execute the following command:
protoc --go_out=plugins=grpc:. helloworld.proto
Copy the code
  1. Proto: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.
  2. Helloworld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld.pb. go: helloWorld On the server side, the GreeterServer interface is implemented by specific business code, and the RegisterGreeterServer method is called to register, so that the service remotely invoked by the client can implement the business function:
func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) {
	s.RegisterService(&_Greeter_serviceDesc, srv)
}

type GreeterServer interface {
	// The specific remote service method
	SayHello(context.Context, *HelloRequest) (*HelloReply, error)
}
Copy the code
  1. With the help of GoLand’s Structure panel, you can take a closer look at helloWorld.pb. go:

Write the server-side code server.go and start it

  1. In $GOPATH/ SRC/helloWorld, create a new folder server.
package main import ( "context" "log" "net" "google.golang.org/grpc" pb "helloworld" ) const ( port = ":50051" ) // Type server struct {// pb.go (struct, struct, struct, struct, struct, struct, 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 argument log.printf ("Received: %v", in.getName ()) // instantiate the structure HelloReply as the return value return & pb.helloReply {Message: Func main() {lis, err := net.listen (" TCP ", port) if err! = nil { log.Fatalf("failed to listen: %v", err)} // Instantiate gRPC server structure s := grpc.newServer () // service registration 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 the go Run server.go command in the directory where server.go resides.
[golang@centos7 server]$go run server.go 2020/12/13 08:20:32Copy the code
  1. At this point, the server of gRPC has been started and can respond to remote calls. Next, the client code is developed.

Write the client code client.go and start it

  1. Open another console;
  2. Create client in $GOPATH/ SRC/helloWorld and create client.go in this folder.
package main

import (
	"context"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	pb "helloworld"
)

const (
	address     = "localhost:50051"
	defaultName = "world"
)

func main(a) {
	// Connect to the server remotely
	conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
	iferr ! =nil {
		log.Fatalf("did not connect: %v", err)
	}

	// Close the remote connection after the main method is complete
	defer conn.Close()

	// Instantiate the data structure
	c := pb.NewGreeterClient(conn)

	// Request parameters for remote calls, if not passed in from the command line, use default values
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]}// Set timeout
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)

	defer cancel()

	// Remote call
	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
	iferr ! =nil {
		log.Fatalf("could not greet: %v", err)
	}

	// Print the information returned by the server
	log.Printf("Greeting: %s", r.GetMessage())
}
Copy the code
  1. Run client. Go in the client. Go directory, the system immediately initiates a remote call to the server.
[golang@centos7 client]$ go run client.go
2020/12/13 08:38:05 Greeting: Hello world
Copy the code
  1. Go to the console on the server side and check the log to see that the business code was executed and the parameters of the remote request were received:
[golang@centos7 server]$go run server.go 2020/12/13 08:20:32 2020/12/13 08:38:05 Received: worldCopy the code
  1. Go back to the client console, try the command line with parameters, enter go run client.go ABC, and receive the following response from the server:
[golang@centos7 client]$ go run client.go abc
2020/12/13 08:56:36 Greeting: Hello abc
Copy the code
  1. Check the console on the server side and receive ABC successfully:
[golang@centos7 server]$go run server.go 2020/12/13 08:20:32 2020/12/13 08:38:05 Received: world 2020/12/13 08:56:36 Received: abcCopy the code
  • At this point, a conventional gRPC development combat is completed, I hope to give you some reference, the next article we will continue to in-depth study;

You are not alone, Xinchen original accompany 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 pay attention to the public number: programmer Xin Chen

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

Github.com/zq2599/blog…