How to quickly start GRPC service? (explain Proto compilation service and GRPC startup service in detail)

In the last article, we only defined one model, and also defined a model of input and output parameters.

In this article, let's continue to define the interface and let it run at the same time.

Define a service

Write proto file

Create a new file under the / protps directory called service Proto, as follows:

syntax="proto3";
option go_package = "k_grpc/pbFiles";

import "models.proto"; //Import the required model

service StudentService {
  rpc GetStudent (GetStudentRequest) returns (GetStudentResponse);
}
copy

I don't think it needs to be introduced in detail. This is very similar to the grammar of Go.

If you don't understand, please leave a message and answer for you.

compile

Now we need to compile the grpc service, so we also need a dependency package. Otherwise, we can't compile it.

The installation method of dependent package is also very simple. Just execute the command directly. The command is as follows:

go get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc
copy

After the dependency package is installed, a protocol Gen go grpc file will appear in the bin directory of your GOPATH, as shown in the following figure:

When the dependency package is installed, it can be compiled.

The compiling command this time is different from that of the previous one. The commands are as follows:

protoc --proto_path=protos --go-grpc_out=./../ service.proto
copy

Changes:

- go is no longer used here_ Out, but use -- go grpc_ Out, because we need to compile the grpc service.

After compiling, there will be another one named service under your / pbFiles directory_ grpc. pb. Go file.

At this time, the grpc package will be missing. Let's install the dependent package. The command is as follows:

go get google.golang.org/grpc
copy

Implement a service

So far, we have defined the request model and service interface, but to make the service run, we still need to implement the corresponding service.

After all, so far, we have only defined the service, and we haven't written a line of code, just as we have written the interface document but haven't written the code.

Now you need to create a new folder named services under the project and a new folder named studentservice Go file with the following contents:

package services

import (
 "context"
 "k_grpc/pbFiles"
)

type StudentService struct {
 // The introduction of Google helps us realize some functions of the structure
 pbFiles.UnimplementedStudentServiceServer
}

// To implement the interface we defined
func (this *StudentService) GetStudent(_ context.Context, req *pbFiles.GetStudentRequest) (*pbFiles.GetStudentResponse, error) {
 // Business logic is implemented here
 rsp := &pbFiles.GetStudentResponse{
  Result: &pbFiles.Student{
   Id: req.SId,
   Name: "[GoLang [full stack] Writing",
  },
 }
 return rsp,nil
}

func NewStudentService() *StudentService {
 return &StudentService{}
}
copy

Start a service

When our model and service are defined, we can start the service.

Let's start the server and create a new one named server under the root directory of the project Go file with the following code:

package main

import (
 "google.golang.org/grpc"
 "k_grpc/pbFiles"
 "k_grpc/services"
 "log"
 "net"
)

func main() {
 // Create a GRPC service
 srv := grpc.NewServer()
 // Register services that need to be mounted
 pbFiles.RegisterStudentServiceServer(srv, services.NewStudentService())
 // Start a listening service
 lis,_ := net.Listen("tcp",":8080")
 // Start GRPC service
 if err := srv.Serve(lis);err != nil{
  log.Fatalln(err)
 }
}
copy

This part of the code should not need to be explained too much. There is nothing particularly difficult to understand.

Now let's start and directly execute:

$ go run server.go
copy

If nothing is output and hung there, it means that the startup is successful.

Create client

The code is as follows:

package main

import (
 "context"
 "fmt"
 "google.golang.org/grpc"
 "k_grpc/pbFiles"
 "log"
)

func main() {

 // Create connection end
 target := "localhost:8080"
 client,err := grpc.DialContext(
  context.Background(),
  target,
  grpc.WithInsecure(),
 )
 if err != nil {
  log.Fatalln(err)
 }

 // Define request body
 req := &pbFiles.GetStudentRequest{
  SId: 3333,
 }
 // Define return body
 rsv := &pbFiles.GetStudentResponse{}

 // Formal request
 _ = client.Invoke(
  context.Background(),
  "/StudentService/GetStudent",
  req,
  rsv)

 // Printout
 fmt.Println(rsv.Result)
}
copy

Note:

1. At present, we have not introduced the certificate verification mechanism.

So you can see what I used when creating the connection terminal: grpc Withsecure() cannot be used in production. Certificate verification mechanism must be introduced.

2. In the formal request, we use the most original way.

Of course, GRPC also provides encapsulated calls, but it's better for novices to understand this process before upgrading.

So the code "/ StudentService/GetStudent" represents the service and method we want to call.

Operation effect diagram:

Here, our service has been started and can be called, but there is no access certificate.

Next we write: how to access certificate one-way verification, please look forward to!

Posted by Bopo on Tue, 10 May 2022 03:43:11 +0300