golanggolang技术程序员

grpc for golang

2017-11-27  本文已影响221人  一字马胡

作者: 一字马胡
转载标志 【2017-11-27】

更新日志

日期 更新内容 备注
2017-11-27 新建文章 一个简单的go语言使用grpc的例子

本文将简单介绍如何使用grpc,grpc支持多种语言,本文使用golang进行代码编写,下面将详细介绍如何一步一步完成一个完整可运行的grpc应用,安装golang的步骤就省略了。

install grpc

首先你需要安装grpc,下面的命令可以完成这样事情。


go get google.golang.org/grpc

install protoc

使用grpc还需要安装protobuf,安装下面的命令可以进行编译安装。


git clone https://github.com/google/protobuf
cd protobuf
./configure
make & make install

install gen-code-plug

grpc的服务端是使用IDL文件来描述所能提供的服务的,你需要安装gen-code-plug来将IDL文件翻译为go代码,然后才能进行相应的服务端开发,有几个可供选择的gen-code-plug,下面列出了每种gen-code-plug的安装方法,推荐使用protoc-gen-gofast,因为生成代码的速度很快。


1、choose protoc-gen-gogo

 -> go get github.com/gogo/protobuf/protoc-gen-gogo
 
2、choose protoc-gen-gofast

-> go get github.com/gogo/protobuf/protoc-gen-gofast

3、choose protoc-gen-go

->go get github.com/golang/protobuf/protoc-gen-go

write proto file (IDL)

现在,可以来写grpc的server端能提供的rpc服务了,下面是一个简单的IDL文件描述细节:


syntax = "proto3";

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 greetings
message HelloReply {
    string message = 1;
}


syntax = "proto3"代表使用protobuf 3来进行代码生成,package定义了生成代码的package,service关键字代表rpc服务端能提供的服务,使用message关键字来定义数据结构,上面的IDL描述的rpc服务端能提供一个称为SayHello的方法,该方法接收一个类型为HelloRequest的入参,返回一个类型为HelloReply的结果。需要将该IDL文件命名为后缀名为“.proto”的文件。

gen go code according to IDL file

有了IDL文件之后,就可以使用protoc来生成go代码了,下面描述了使用不同的plug来生成代码的命令,上文说过推荐使用gofast,可以自行进行对比。



protoc-gen-gogo -> protoc --go_out=plugins=grpc:. *.proto    


gogo -> protoc --gogo_out=. *.proto


gofast -> protoc --gofast_out=. *.proto (Recommend !!!)

运行上面的命令之后,会生成一个后缀为“.pb.go”的go源代码文件,该文件内容较多就不在此展示了。

implement server

执行完上面的步骤之后,现在就可以来实现rpc的服务端了,下面是本例的server端实现细节:


package main

import (
"log"
"net"

"golang.org/x/net/context"
"google.golang.org/grpc"
pb "helloworld/helloworld"
"google.golang.org/grpc/reflection"
)

const (
    port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
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.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

具体的步骤就是首先实现rpc服务端的接口,然后启动rpc服务端,将能提供的服务注册到grpc中去,然后就可以响应rpc客户端的请求了。

implement client (Call Server)

为了测试上面的rpc服务端是否可以正常工作,可以运行下面的go代码来测试:


package main

import (
    "log"
    "os"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    pb "helloworld/helloworld"
)

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)
}


至此,一个简单的使用grpc的例子就完成了,当然,更为复杂的grpc应用也可以参考该例子来进行扩展,只需要按照一定的步骤即可。

文/一字马胡
上一篇 下一篇

猜你喜欢

热点阅读