GRPC Golang Learning Experience (1)----Installation and testing

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go language small white, recently began to contact GRPC, hereby record.

                         ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                           

1.GRPC Installation

Grpc is a high-performance, open-source, common RPC framework for mobile and HTTP/2 design, the first protocol buffers-based RPC framework released by Google.

currently GRPC provides C , JAVA, go language version, the code is hosted on GitHub, grpc,  grpc-java,  Grpc-go c c++ node.js Python ruby Objective-c php  and   C#

This article only describes the installation and use of grpc-go.

1.1 Check the Go language version

$go Versiongo version go1.6.3 linux/amd64

GRPC requires the Go language version to be at least 1.5 +, the version is too low, please first update the Go language version:Getting started-the go programming Language

1.2 Installing GRPC

$ go Get google.golang.org/grpc

1.3 Installing Protocol buffers v3

Protocol buffer is used to generate the GRPC service code.

To install the Protoc plugin for go:

$ go get-u github.com/golang/protobuf/{proto,protoc-gen-go}
The compiler plugin Protoc-gen-go is installed in the $gobin directory, in order to ensure that the compiler Protoc can find the Protoc-gen-go plug-in, the $gopath is imported into the $path path:

Export path= $PATH: $GOPATH/bin
echo $PATH     //view $path

GRPC installation is complete!


2. Test GRPC

2.1 Defining the Service


An RPC service is a method that can be called remotely through parameters and return values, and we can simply interpret it as a function. Because GRPC is transmitted by encoding the data into protocal buffer. Therefore, we define the service method by Protocal buffers Interface Definitioin language (IDL), and also define the parameter and return value as the protocal buffer message type. The specific implementation is as follows, create a HelloWorld folder, edit the Helloworld.proto file:

Syntax = "Proto3"; Option Java_package = "Io.grpc.examples"; Package HelloWorld; The Greeter service definition.service greeter {  //sends a greeting  RPC SayHello (hellorequest) returns (Hello Reply) {}}//The request message containing the user ' s name.message hellorequest {  string name = 1;}//The response Message containing the Greetingsmessage helloreply {  string message = 1;}

2.2 Using protocal buffer compiler to generate the corresponding Golang code

Based on the service defined above, we can use protocal buffer compiler, the PROTOC, to generate the corresponding Golang code for the server side and client. The generated code contains the methods that the client can make RPC and the interfaces that the server side needs to implement.

Assuming the current directory is $gopath/src/helloworld/helloworld, we will generate the GRPC corresponding Golang code with the following command:

Protoc--GO_OUT=PLUGINS=GRPC:. Helloworld.proto
At this point, the Helloworld.pb.go file is generated under the directory.

2.3 Test GRPC Service

Create Server.go and Client.go under directory $gopath/src/helloworld/, respectively, for the server and client implementations.

Server.go

Package main//Server.go import (    "log"    "NET"     "Golang.org/x/net/context"    "Google.golang.org/grpc"    PB "Helloworld/helloworld") const (    port = ": 50051") type server struct {} func (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. Fatal ("Failed to listen:%v", err)    }    S: = Grpc. NewServer ()    PB. Registergreeterserver (S, &server{})    S.serve (LIS)}

Client.go

Package main//client.go Import (    "log"    "OS"     "Golang.org/x/net/context"    "Google.golang.org/grpc"    PB "Helloworld/helloworld") const (    address     = "localhost:50051"    defaultname = "World") Func main () { C10/>conn, err: = Grpc. Dial (address, grpc. Withinsecure ())    if err! = Nil {        log. Fatal ("Did not connect:%v", err)    }    defer conn. Close ()    c: = PB. Newgreeterclient (conn)     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. Fatal ("Could not greet:%v", err)    }    log. Printf ("Greeting:%s", R.message)}
* * * It is important to note that the package PB is the package of the helloworld.pb.go we generated earlier, not necessarily in the $gopath/src/helloworld/helloworld directory as shown in the code above.

2.4 Running Server/client.go

$ go Run greeter_client/main.go

Go Run server.go
Re-open a terminal go run client.go

2.5

Note: If you are installing GRPC through go get google.golang.org/grpc , in $GOPATH/src/google.golang.org/grpc/examples The test case is already included in the directory

switch to the examples directory
$ cd $GOPATH/src/google.golang.org/grpc/examples/helloworld
Run Server/client.go
$ go Run greeter_server/main.go
$ go Run greeter_client/main.go
Running successfully, the terminal output of the client will be: Greeting:hello World


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.