Introduction to gRPC experience and grpc experience

Source: Internet
Author: User
Tags automake

Introduction to gRPC experience and grpc experience

GRPC is an RPC framework developed by Google. It uses HTTP/2 protocol and ProtoBuf as the serialization tool. The client provides Objective-C and Java interfaces, while the server side provides interfaces such as Java, Golang, and C ++, so as to provide mobile terminals (iOS/Androi) communication to the server provides a solution. Of course, in the current environment, the more popular solution is the RESTFull API interface. This method requires you to select the encoding method, server architecture, build your own framework (JSON-RPC ). GRPC's official voice on REST is:

Like REST, it follows the HTTP protocol (HTTP/2), but gRPC provides a full-duplex stream. Unlike traditional REST, gRPC uses a static path, this improves performance by replacing HTTP status codes with formatted error codes to better mark errors.

Select whether to use gRPC. For a team that already has a set of solutions, refer. If you do this from the beginning, you can consider the entire solution from the client to the server provided by gRPC, so that the client does not need to parse http request sessions, JSON, etc, the server also has a ready-made framework. Since March, gRPC has also developed for a year and has gradually matured. Next we will take gRPC's Golang version to see its performance on golang. As for the RPC on the server end, it seems that the RPC framework of the golang standard library is basically enough, and there is no need to use another solution.

1. Install protobuf

Although gRPC also supports protobuf2.x, it is recommended that protobuf3.x be used. Although protobuf3.x is not in the official version, golang version is basically no problem. x officially supports Objective-C, which is also the original intention of gRPC: to provide a mobile-to-server solution. Go to Protocol Buffers to download the latest version (Version3.0.0 beta2), and decompress the package to your local device. Local needs have been installedAutoconf automake libtool. rpm series (fedora/centos/redheat) can be installed using yum. Brew can be used for installation on Mac

brew install autoconf automake libtool

Then execute

./configure --prefix=your_pb_install_path

Next

make make installset your_pb_install_path to your $PATH

Check whether installation is complete

protoc --versionlibprotoc 3.0.0

Then install golang protobuf and use golang's get directly.

Go get-u github.com/golang/protobuf/proto // golang protobuf library go get-u github.com/golang/protobuf/protoc-gen-go // protoc -- go_out Tool
2. Install gRPC-go

GRPC-go can be directly installed using the get command of golang, which is very convenient.

go get google.golang.org/grpc

Here you may be strange, why gRPC-go address in github is "https://github.com/grpc/grpc-go", but why to use "google.golang.org/grpc#to install it? Grpc was originally a google internal project, belonging to golang, which was placed under google.golang.org. later it was opened to the outside and migrated to github, and because golang is more confused about the import path rules, no path name has been changed.

But there is a problem. How to manage versions? At present, I have no better method. I hope you can share it with me. Currently, one method is to manually download a version, and then write a script to modify the path in the import in the code.

3. Sample program 3.1 protobuf

This example is from the helloworld of examples in gRPC-go. Let's first look at the description of PB:

syntax = "proto3";option objc_class_prefix = "HLW";package helloworld;// The greeting service definition.service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {}}// The request message containing the user's name.message HelloRequest { string name = 1;}// The response message containing the greetingsmessage HelloReply { string message = 1;}

A service Greeter is defined here, with an APISayHello. The accepted parameter isHelloRequest type, returnHelloReply type. HereHelloRequest andHelloReply is a general PB definition.

The service is defined:

// The greeting service definition.service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {}}

Service defines a server. The interface can be of four types.

Rpc GetFeature (Point) returns (Feature ){}
Similar to common function calls, the client sends a request Point to the server, and the server returns the Feature. rpc ListFeatures (Rectangle) returns (stream Feature ){}
When a client initiates a request, the server returns a streaming data, for example, rpc RecordRoute (stream Point) returns (RouteSummary) (one by one element in an array ){}
The request initiated by the client is a streaming data. For example, if the elements in the array are one by one, the server returns a corresponding rpc RouteChat (stream RouteNote) returns (stream RouteNote ){}
A request initiated by a client is a streaming data, such as element-by-element in an array. The two servers return a similar data structure.

Use the protoc command to generate related files:

protoc --go_out=plugins=grpc:. helloworld.protolshelloworld.pb.go helloworld.proto

Generate the corresponding pb. go file. The plugins option is used to support grpc. Otherwise, the Service interface is not generated.

3.2 server programs

Then edit the server program:

package mainimport ( "log" "net" pb "your_path_to_gen_pb_dir/helloworld" "golang.org/x/net/context" "google.golang.org/grpc")const ( port = ":50051")// server is used to implement helloworld.GreeterServer.type server struct{}// SayHello implements helloworld.GreeterServerfunc (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil}func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) s.Serve(lis)}

Here, we first define a server structure and then implement the SayHello interface, which is defined in "your_path_to_gen_pb_dir/helloworld"

SayHello(context.Context, *HelloRequest) (*HelloReply, error)

Then callGrpc. NewServer () creates a server s. Then register the server s to the schema server.Pb. RegisterGreeterServer (s, & server {}) Finally passes the created net. ListenerS. Serve (). You can start listening and service, similar to HTTP ListenAndServe.

3.3 client program

Client Program:

package mainimport ( "log" "os" pb "your_path_to_gen_pb_dir/helloworld" "golang.org/x/net/context" "google.golang.org/grpc")const ( address = "localhost:50051" defaultName = "world")func main() { // Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) // Contact the server and print out its response. name := defaultName if len(os.Args) > 1 { name = os.Args[1] } r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message)}

Here, a conn is passed in through pb. NewGreeterClient () to create a client, and then the corresponding server interface above the client is called directly.

SayHello(context.Context, *HelloRequest) (*HelloReply, error)

Interface, returns the * HelloReply object.

Run the server first. You can see it when running the client.

./greeter_server &./greeter_client


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.