GRPC simple to use

Server code github.com/Charlotte32…

Client code github.com/Charlotte32…

1. Install the protobuf

brew install protobuf
Copy the code

2. Create a Go program

go mod init moudleName
Copy the code

3. Install the GRPC

go get -u google.golang.org/grpc
Copy the code

4. Install the protobuf plug-in (protoc-gen-go) to generate pb.go pb_grpc.go

go get -u google.golang.org/protobuf/cmd/protoc-gen-go
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
Copy the code

After installation, go to the bin directory in go env GOPATH to check whether protoc-gen-go is generated

5. Write.proto files

Syntax document: developers.google.com/protocol-bu…

touch Hello.proto
vi Hello.proto
Copy the code
syntax = "proto3"; / / version number
package services; // Which package to put the generated files in

option go_package = "nsqk.com/rpc";

message SayHelloRequest{
  string name = 1;
}

message HelloReplay{
  string message = 1;
}
Copy the code

6. Generate the pb.go file

cd.Create a services folder because package in proto says services
mkdir services 
cdpb/ protoc --go_out=.. /services Hello.protoCopy the code

7. Compile RPC Service

syntax = "proto3"; / / version number
package services; // Which package to put the generated files in

option go_package = "nsqk.com/rpc";

message SayHelloRequest{
  string name = 1;
}

message HelloReplay{
  string message= 1; } // Write belowrpcInterface service HelloWorld{
	rpc HelloRPC (SayHelloRequest) returns (HelloReplay) {}}Copy the code

8. Generate the. Pb_grpc file

cdpb protoc --go_out=.. /services --go_opt=paths=source_relative \ --go-grpc_out=.. /services --go-grpc_opt=paths=source_relative \ Hello.protoCopy the code

Grpc-getway provides both RESTful and gRPC interfaces

Operations related to certificates juejin.cn/post/702550…

1. Install

  1. Create a new tool folder and create tool.go
  2. Import the required packages
package tool
import(_"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway"
	_ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2"
	_ "google.golang.org/grpc/cmd/protoc-gen-go-grpc"
	_ "google.golang.org/protobuf/cmd/protoc-gen-go"
)
Copy the code
  1. go mod tidy

  2. Install the plug-in in the Go bin directory.

    go install \
        github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
        github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \
        google.golang.org/protobuf/cmd/protoc-gen-go \
        google.golang.org/grpc/cmd/protoc-gen-go-grpc
    Copy the code
  3. Copy the Google folder below the PB folder

    Cp/Users/jr/go/pkg/mod/github.com/grpc-ecosystem/[email protected]/third_party/googleapis/google. / pb /Copy the code

2. Create a prod. proto

syntax = "proto3"; / / version number
package services; // The package name of the generated file

option go_package = ".; services"; // To override the package name above; In front is the path

import "google/api/annotations.proto";

message ProdRequest{
  int32 prod_id = 1; Id / / commodities
}

message ProdResponse{
  int32 prod_stock = 1; / / inventory
}

message QuerySize{
  int32 size = 1; / / page size
}

message ProdResponseList{ // Return the inventory list
  repeated ProdResponse prodres = 1;
}


service ProdService{
  rpc GetProdStock(QuerySize) returns (ProdResponseList){
    option (google.api.http) = {
      get: "/v1/prod/{size}"}; }}Copy the code

3. Regeneratepb.go _grpc.pb.go, and generate the new Gatewaypb.gw.go

Generate prod.pb. go and prod_grpc.pb. go

cdpb && protoc --go_out=.. /services --go_opt=paths=source_relative \ --go-grpc_out=.. /services --go-grpc_opt=paths=source_relative \ Hello.protoCopy the code

Generate the Prod. Pb. Gw. Go

protoc -I . \ --grpc-gateway_out .. /services \ --grpc-gateway_opt logtostderr=true \
       --grpc-gateway_opt paths=source_relative \
           Prod.proto
Copy the code

4. Write the ProdService file

package services

import (
	"context"
	"log"
)

type ProdService struct{}func (p *ProdService)GetProdStock(ctx context.Context, req *QuerySize) (*ProdResponseList, error){
	log.Println(req.Size)
	return &ProdResponseList{Prodres: []*ProdResponse{&ProdResponse{ProdStock: 2333}}},nil
}
func (p *ProdService)mustEmbedUnimplementedProdServiceServer(a){
	log.Fatalln("Contains unimplemented service")}Copy the code

5. Write an HTTP service file

package main

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"log"
	"net/http"
	"nsqk.com/rpc/helper"
	"nsqk.com/rpc/services"
)

func main(a) {
	ctx := context.Background()
	ctx,cancel := context.WithCancel(ctx)
	defer cancel()

	Create a Gateway MUx
	gwmux := runtime.NewServeMux()
	// Create the GRPC Client Dial configuration item
	// The RESTful API is turned into the gRPC client to request, so the client certificate is passed in
	opt := []grpc.DialOption{grpc.WithTransportCredentials(helper.GetClientCreds())}
	// Register and set the HTTP handler, where the endpoint passed in is the address of the gRPC server
	err := services.RegisterHelloWorldHandlerFromEndpoint(ctx,gwmux,"localhost:2333",opt)
	iferr ! =nil{
		log.Fatalln("Failed to register hello GRPC forwarding :",err)
	}
	err = services.RegisterProdServiceHandlerFromEndpoint(ctx,gwmux,"localhost:2333",opt)
	iferr ! =nil{
		log.Fatalln("Failed to register prod GRPC forwarding :",err)
	}
	httpServer := &http.Server{
		Addr: ": 23333",
		Handler: gwmux,
	}
	err = httpServer.ListenAndServe()
	iferr ! =nil{
		log.Fatalln("HTTP startup failed :",err)
	}


}
Copy the code

6. Start

  1. Start the grpcServer
  2. Restart the httpServer

The GRPC port is 2333 and the HTTP port is 23333

At the end

At this point, both HTTP and GRPC are accessible

Demo code address:

Client: github.com/Charlotte32…

Server: github.com/Charlotte32…