Go Micro's service is simple to use grpc


Author: Wen Wen Wei
link: https: //www.jianshu.com/p/20ed82218163
Source: Jane books

Ready to work

Install Protobuf compiler protoc, Download: https://github.com/google/protobuf/releases
I are windows, under the exe archive directory into the bin directory to PATH environment.

Then get the plug-in support library

// gRPC运行时接口编解码支持库

  go get -u github.com/golang/protobuf/proto 
// 从 Proto文件(gRPC接口描述文件) 生成 go文件 的编译器插件
go get -u github.com/golang/protobuf/protoc-gen-go

GRPC go get the package (network problems can be found https://www.jianshu.com/p/6392cb9dc38f )

  go get google.golang.org/grpc

  

Interface file / src /

New test.protoexample:

 syntax = "proto3";
  // define the package name
  package test;
  
  // You can define multiple services, you can define multiple interfaces within each service
  service Waiter {
    // definition of the interface (the structure may be multiplexed)
    // Method (Request message structure) Returns (returns the message structure) {}
    rpc DoMD5 (Req) returns (Res) {}
  }

  // definition of message structure Req
  message Req {
    // Type field identification number =
    string jsonStr = 1;
  }

  // definition of message structure Res
  message Res {
    string backJson = 1;
  }
// PS: jsonStr and backJson just hand write the name, did not use json

Detailed proto file syntax see: https://blog.csdn.net/u014308482/article/details/52958148

Then put the compiled files go proto file

  // protoc --go_out = plugins = grpc: {} {proto output directory file}
  protoc --go_out=plugins=grpc:./test/ ./test.proto

Note: To modify the principle of compiled *.bp.gocode file, since the two sides based on the interface with a proto documents translated into their own language source code, this document only as the interface data processing, business is not in the specific implementation *.bp.goin.

Server / src / server /

I am also new to Go, based https://github.com/freewebsys/grpc-go-demo the Demo understanding gRPC modification in
which the Chinese understand the comments are personal notes, if not rigorous place, but also look correction.

 package main
    import (
        "log"
        "net"
        "golang.org/x/net/context"
        "google.golang.org/grpc"
        "test"
        "google.golang.org/grpc/reflection"
        "fmt"
        "crypto/md5"
    )

    // implementation of container business
    type server struct{}

    // define DoMD5 method for the server processes the request and returns the result of the internal
    // Parameter (context.Context [stationary], * test.Req [corresponding interface definition request parameter])
    // returns (* test.Res [return parameter corresponding interface definition, must be a pointer], error)
    func (s *server) DoMD5(ctx context.Context, in *test.Req) (*test.Res, error) {
        fmt.Println ( "MD5 method request JSON:" + in.JsonStr)
        return &test.Res{BackJson: "MD5 :" + fmt.Sprintf("%x", md5.Sum([]byte(in.JsonStr)))}, nil
    }

    func main() {
        lis, err: = net.Listen ( "tcp", ": 8028") // listen on all LAN ports TCP 8028 connection
        if err != nil {
            log.Fatalf ( "monitor failed:% v", err)
        }
        s: = grpc.NewServer () // create gRPC service

        / ** Registration Interface service
         * The service time is defined as a unit proto registered, you can have multiple methods of service
         * (For each service will generate Register *** Server method proto compile time)
         * Package registered service method (GRPC service instance, the structure comprises an interface method [pointers])
         */
        test.RegisterWaiterServer(s, &server{})
        / * If there are a plurality of interface service can be registered, the structure to achieve the corresponding interface method
         * user.RegisterLoginServer(s, &server{})
         * minMovie.RegisterFbiServer(s, &server{})
         */
        // Register reflection service on the server gRPC
        reflection.Register(s)
        // will listen to gRPC processing services
        err = s.Serve(lis)
        if  err != nil {
            log.Fatalf("failed to serve: %v", err)
        }
    }

  

Client / src / client /

  package main
        import (
            "log"
            "os"
            "golang.org/x/net/context"
            "google.golang.org/grpc"
            "test"
        )
    
    
        func main() {
            // establish a connection to the service gRPC
            conn, err := grpc.Dial("127.0.0.1:8028", grpc.WithInsecure())
            if err != nil {
                log.Fatalf("did not connect: %v", err)
            }
            // close the connection at the end of the function
            defer conn.Close()
    
            // Create Waiter service clients
            t := test.NewWaiterClient(conn)
    
            // analog data request
            res := "test123"
            // os.Args [1] for the user to perform input parameters such as: go run *** go 123.
            if len(os.Args) > 1 {
                res = os.Args[1]
            }
    
            // Call gRPC Interface
            tr, err := t.DoMD5(context.Background(), &test.Req{JsonStr: res})
            if err != nil {
                log.Fatalf("could not greet: %v", err)
            }
            log.Printf ( "server response:% s", tr.BackJson)
        }

Start the server monitor, you can run the client to achieve remote call

image.png



Guess you like

Origin www.cnblogs.com/-wenli/p/11839272.html