grpc Practice II: environment construction and simple demo

Grpc Practice II: environment construction and simple demo

2.1 grpc environment installation

2.1.1 golang environment installation

All the following tutorials and codes are demonstrated by golang code, so we need to install golang environment: download address: golang official website

After installation, enter in your command line tool

go version

You can see the corresponding download version

Then you can.

2.1.2 protoc ol installation

In gRPC development, we often need to deal with Protobuf. After writing the. proto file, we need a compiler, protoc. This tool can be downloaded directly on GitHub

https://github.com/protocolbuffers/protobuf/releases

You can download and install on this website by yourself (because you don't want to reinstall it after the installation here. You may not remember clearly. Just try it directly and enrich it after the next reinstallation). The general operation is to configure the directory where the protoc ol compiled file is located into the environment variable. After the installation:

function

protoc --version

You can see the version information

2.1.2 install related dependent packages

Install the proto toolkit for golang

go get -u github.com/golang/protobuf/proto

Install proto compilation support for goalg

go get -u github.com/golang/protobuf/protoc-gen-go

Install gRPC package

go get -u google.golang.org/grpc

This basically completes the installation of the environment

2.2 grpc simple demo

2.2.1 protocol buffer syntax

In gRPC, APIs and services are mainly defined by protocol buffer, so we need to understand the syntax of protocol buffer first. There are two versions of protocol buffer: proto2 and proto3. Here, we recommend that you use proto3 for daily development.

Refer to Google's documentation for the protocol buffer proto3 version Language Guide (proto3) Or Qiannian Feiyu greatly translated Protobuf3 Language Guide.

Next is a simple protocol buffer demo on the official website:

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//Specify proto3 syntax
syntax = "proto3";

//Output to current directory
option go_package = "./";
//Package name
package helloworld;

// hello service (multiple services can be defined, and each service can define multiple methods)
service Greeter {
  // hello service entry
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// Define send request information
message HelloRequest {
  // Define parameters to send
  // Parameter type parameter name identification number (non repeatable)
  string name = 1;
}

// Define response information
message HelloReply {
  string message = 1;
}

2.2.2 compiling proto files

Before compiling the file, let's build the simplest project directory

greeter_client: gRPC client code

helloworld: store public pb files and compiled files

greeter_server: gRPC server code

You can directly generate the code of the corresponding language through the following command. See the specific code:

protoc --go_out=plugins=grpc:. *.proto

2.2.3 writing server code

// Package main implements a server for Greeter service.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net"

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

//Define port
var (
	port = flag.Int("port", 50051, "The server port")
)

// server is used to implement helloworld.GreeterServer
type server struct {
	pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Printf("Received: %v", in.GetName())
	return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func main() {
	flag.Parse()
	// Listen on local port
	lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	// New gRPC server instance
	s := grpc.NewServer()
	// Register our service with gRPC server
	pb.RegisterGreeterServer(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	//Use the server Serve() method and our port information area to realize blocking and waiting until the process is killed or Stop() is called
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

Visible to the running client:

2.2.4 writing client code

package main

import (
	"context"
	"flag"
	"log"
	"time"

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

const (
	defaultName = "world"
)

var (
	addr = flag.String("addr", "localhost:50051", "the address to connect to")
	name = flag.String("name", defaultName, "Name to greet")
)

func main() {
	flag.Parse()
	// Connect server
	conn, err := grpc.Dial(*addr, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	// Establish gRPC connection
	c := pb.NewGreeterClient(conn)

	// Contact the server and print out its response.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	
	// Call our service (SayHello method)
    // At the same time, a context.Context is passed in. If necessary, we can change the behavior of RPC, such as timeout / canceling a running RPC
	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: *name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	// Print return value
	log.Printf("Greeting: %s", r.GetMessage())
}

Visible after operation:

At the same time, the server also has the following display

2.3 BloomRPC open source client

Students familiar with Restful development process know that after writing the server, a client tool is needed to test the interface. BloomRPC is a good grpc GUI tool, similar to Postman

Usage reference:

https://juejin.cn/post/6944670144392069134

Bloom RPC test demo above

1. Import the defined proto as follows

2. Click the Green run button

summary

In this way, a simple service and client are built so that they can interact easily

Tags: Go Linux CentOS

Posted on Wed, 01 Dec 2021 11:22:16 -0500 by melbell