Golang Grpc Example

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

1. Install GRPC Runtime

Go get Google.golang.org/grpc

  

To automatically generate the Golang GRPC code, you need to install protocal buffers compiler and the corresponding Golang plug-in

2, protocal buffer installation

Download the installation package from Https://github.com/google/protobuf/releases, for example: Protobuf-cpp-3.0.0-beta-3.zip, after decompression

./configuremake && Make Install

  

Add environment variable: Export ld_library_path=/usr/local/lib, then PROTOC command to run

3. Install Golang PROTOC plug-in

Go get-a github.com/golang/protobuf/protoc-gen-go

  

4. Define 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, the file containing the following code is called Helloworld.proto:

Syntax = "Proto3"; option Java_package = "Io.grpc.examples";p ackage helloworld;//the greeter service Definition.service G  Reeter {  //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;}

  

5, then, according to the service defined above, we can use protocal buffer compiler, that is PROTOC generate the corresponding server side and client Golang code. 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.

6. Next, create Server.go and Client.go under directory $gopath/src/helloworld/, respectively, for server and client implementations.

Package main//Server.goimport ("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)}

  

  

Package main//client.goimport ("Log" "OS" "Golang.org/x/net/context" "Google.golang.org/grpc" PB "helloworld/ HelloWorld ") const (address=" localhost:50051 "Defaultname=" World ") Func main () {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: = Defaultnameif 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 preceding code.

7, finally run the following code for demonstration can be

Go run Server.gogo Run Client.go

  

Related Article

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.