Simple use of go zero micro service framework rpc

Following the previous article, according to the idea of "automatic operation and maintenance scheme for terminal delivery", https://blog.csdn.net/yyz_1987/article/details/118358038

Take the above sending terminal status as an example, record the simple use of go zero micro service, and realize a simple background monitoring cloud service.

Create a new directory of Golang service background project code, named monitor.

Gateway layer implementation

According to the use mode of goctl code generated artifact, first define the interface field information to be submitted by the terminal:

statusUpload.api

type (
	//Content of terminal status report
	StatusUploadReq {
		Sn     string `json:"sn"`     //Equipment unique number
		Pos    string `json:"pos"`    //Terminal number
		City   string `json:"city"`   //City Code
		Id     string `json:"id"`     //Terminal type
		Unum1  uint   `json:"unnum"`  //Number of records not transmitted -- bus
		Unum2  uint   `json:"unnum"`  //Quantity of records not transferred -- Third Party
		Ndate  string `json:"ndate"`  //current date
		Ntime  string `json:"ntime"`  //current time 
		Amount uint   `json:"amount"` //Total on duty
		Count  uint   `json:"count"`  //Number of people on duty
		Line   uint   `json:"line"`   //Line number

		Stime string `json:"stime"` //Startup time
		Ctime string `json:"ctime"` //Shutdown time

		Tenant uint `json:"tenant"` //Tenant ID
	}

	//Response content
	StatusUploadResp {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
		Cmd  int    `json:"cmd"` //Control terminal command word
	}
)

service open-api {
	@doc(
		summary: Open api function
		desc: >statusUpload Terminal status reporting
	)
	@server(
		handler: statusUploadHandler
		folder: open
	)
	post /open/statusUpload(StatusUploadReq) returns(StatusUploadResp)
	
}

Next, with the power of goctl artifact, directly generate the gateway layer code:

goctl api    go    -api       statusUpload.api   -dir    .

The directory structure of generated code is as follows:

Next, run and try:

go run open.go

The gateway layer is started successfully. Listen on port 8888 and open API in the etc folder Configuration in yaml file

Measure with postman and curl tools respectively:

 

curl http://127.0.0.1:8888/open/statusUpload -X POST -H "Content-Type: application/json" -d @status.json

 status.json file content:

{
    "sn": "1C2EB08D",
    "pos": "12345678",
    "city": "0371",
    "id": "B503",
    "unum1": 0,
    "unum2": 0,
    "ndate": "2021-08-07",
    "ntime": "18:30:30",
    "amount": 0,
    "count": 0,
    "line": 101,
    "stime": "05:01:01",
    "ctime": "18:30:20",
    "tenant": 0
}

RPC server implementation

Next, transform it into a microservice, and call the interface provided by the service through rpc. The general structure is as follows:

 

The etcd environment needs to be installed in advance, and some plug-in tools need to be installed, such as proto Exe and proto Gen go Exe tool, put it in the bin directory of go or gopath.

Create an rpc folder under the project code directory and create a code directory on the microservice side, which is called status here.

Define the proto file, status Proto is as follows:

syntax = "proto3";

package status;

message statusUploadReq {
    string sn = 1;
    string pos = 2;
	string city  = 3;
	string id = 4;  
	uint32 unum1 = 5;
	uint32 unum2 = 6;
	string ndate = 7;
	string ntime = 8;
	uint32 amount = 9;
	uint32 count = 10;
	uint32 line  = 11;
	      
	string stime = 12;
	string ctime = 13;
	      
	uint32 tenant = 14;

}

message statusUploadResp {
    int32 code = 1;
    string msg = 2;
    int32 cmd = 3;
}

service statusUploader {
    rpc statusUpload(statusUploadReq) returns(statusUploadResp);
}

Then the goctl artifact became powerful and automatically generated code. Isn't it powerful?

goctl rpc proto -src=status.proto  -dir    .

The automatically generated file directory is as follows:

The client folder is not included. The client folder is created by me to test the rpc service separately. I will make a demo on the client side to call the rpc service.

Automatically generate rpc server status Go entry file content:

package main

import (
	"flag"
	"fmt"

	"monitor/rpc/status/internal/config"
	"monitor/rpc/status/internal/server"
	"monitor/rpc/status/internal/svc"
	"monitor/rpc/status/status"

	"github.com/tal-tech/go-zero/core/conf"
	"github.com/tal-tech/go-zero/zrpc"
	"google.golang.org/grpc"
)

var configFile = flag.String("f", "etc/status.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)
	srv := server.NewStatusUploaderServer(ctx)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		status.RegisterStatusUploaderServer(grpcServer, srv)
	})
	defer s.Stop()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}

At this time, if etcd is started, go run status Go, the server starts successfully.

RPC client test

To verify that the rpc server works normally, implement a zrpc client in the client folder to test:

client.go files are as follows:

package main

import (
	"context"
	"fmt"
	"github.com/tal-tech/go-zero/core/discov"
	"github.com/tal-tech/go-zero/zrpc"
	"log"
	pb "monitor/rpc/status/status"
)

func main() {
	client := zrpc.MustNewClient(zrpc.RpcClientConf{
		Etcd: discov.EtcdConf{
			Hosts: []string{"127.0.0.1:2379"},
			Key:   "status.rpc",
		},
	})
	sclient := pb.NewStatusUploaderClient(client.Conn())
	reply, err := sclient.StatusUpload(context.Background(), &pb.StatusUploadReq{Sn: "test rpc", Pos: "go-zero"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(reply.Msg)
}

If the service is normal, you will receive a response from the server interface.

The gateway layer call is changed to micro service call

The gateway layer can be transformed into the invocation mode of micro services. The changes are not significant, as follows:

Step 1:

The config file under the api\internal\config path in the api directory and the open api. Config file under api\etc Yaml file changes:

 

Step 2:

Servicecontext. In the api directory api\internal\svc path Go file changes:

Step 3:

Statusuploadlogic. In the api\internal\logic directory Go file changes,

So far, the transformation of api gateway layer is completed. You can simulate the access gateway interface address

curl http://127.0.0.1:8888/open/statusUpload -X POST -H "Content-Type: application/json" -d @status.json

Added by Sweets287 on Tue, 28 Dec 2021 11:50:46 +0200