当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go gRPC Hello World

Go gRPC Hello World

2019年11月15日  | 移动技术网IT编程  | 我要评论
概述开始 gRPC 了,这篇文章学习使用 gRPC,输出一个 Hello World。 用 Go 实现 gRPC 的服务端。 用 Go 实现 gRPC 的客户端。gRPC 支持 4 类服务方法,咱们这次实现 单项 RPC 和 服务端流式 RPC。四类服务方法单项 RPC服务端发送一个请求给服务端,从 ...

概述

开始 grpc 了,这篇文章学习使用 grpc,输出一个 hello world。

    用 go 实现 grpc 的服务端。

    用 go 实现 grpc 的客户端。

grpc 支持 4 类服务方法,咱们这次实现 单项 rpc 和 服务端流式 rpc。

四类服务方法

单项 rpc

服务端发送一个请求给服务端,从服务端获取一个应答,就像一次普通的函数调用。

rpc sayhello(hellorequest) returns (helloresponse){}

服务端流式 rpc

客户端发送一个请求给服务端,可获取一个数据流用来读取一系列消息。客户端从返回的数据流里一直读取直到没有更多消息为止。

rpc lotsofreplies(hellorequest) returns (stream helloresponse){}

客户端流式 rpc

客户端用提供的一个数据流写入并发送一系列消息给服务端。一旦客户端完成消息写入,就等待服务端读取这些消息并返回应答。

rpc lotsofgreetings(stream hellorequest) returns (helloresponse) {}

 



双向流式 rpc

两边都可以分别通过一个读写数据流来发送一系列消息。这两个数据流操作是相互独立的,所以客户端和服务端能按其希望的任意顺序读写,例如:服务端可以在写应答前等待所有的客户端消息,或者它可以先读一个消息再写一个消息,或者是读写相结合的其他方式。每个数据流里消息的顺序会被保持。

rpc bidihello(stream hellorequest) returns (stream helloresponse){}

 



安装

安装 protobuf 编译器

brew install protobuf

 



验证:

    protoc --version    
    //输出:libprotoc 3.7.1

 



安装 go protobuf 插件

    go get -u github.com/golang/protobuf/proto    
    go get -u github.com/golang/protobuf/protoc-gen-go

 


安装 grpc-go

go get -u google.golang.org/grpc

 




写个 hello world 服务

    编写服务端 .proto 文件

    生成服务端 .pb.go 文件并同步给客户端

    编写服务端提供接口的代码

    编写客户端调用接口的代码

目录结构

    ├─ hello  -- 代码根目录    
    │  ├─ go_client    
    │     ├── main.go    
    │     ├── proto    
    │         ├── hello    
    │            ├── hello.pb.go    
    │  ├─ go_server    
    │     ├── main.go    
    │     ├── controller    
    │         ├── hello_controller    
    │            ├── hello_server.go    
    │     ├── proto    
    │         ├── hello    
    │            ├── hello.pb.go    
    │            ├── hello.proto

这样创建目录是为了 go_client 和 go_server 后期可以拆成两个项目。

编写服务端 hello.proto 文件

    syntax = "proto3"; // 指定 proto 版本    
    package hello;     // 指定包名    
    // 定义 hello 服务    
    service hello {    
        // 定义 sayhello 方法    
        rpc sayhello(hellorequest) returns (helloresponse) {}    
        // 定义 lotsofreplies 方法    
        rpc lotsofreplies(hellorequest) returns (stream helloresponse){}    
    }    
    // hellorequest 请求结构    
    message hellorequest {    
        string name = 1;    
    }    
    // helloresponse 响应结构    
    message helloresponse {    
        string message = 1;    
    }

 



了解更多 protobuf 语法,请查看:

https://developers.google.com/protocol-buffers/

 



生成服务端 .pb.go

protoc -i . --go_out=plugins=grpc:. ./hello.proto

同时将生成的 hello.pb.go 复制到客户端一份。

查看更多命令参数,执行 protoc,查看 option 。

编写服务端提供接口的代码

 

  // hello_server.go    
    package hello_controller    
    import (    
        "fmt"    
        "golang.org/x/net/context"    
        "hello/go_server/proto/hello"    
    )    
    type hellocontroller struct{}    
    func (h *hellocontroller) sayhello(ctx context.context, in *hello.hellorequest) (*hello.helloresponse, error) {    
        return &hello.helloresponse{message : fmt.sprintf("%s", in.name)}, nil    
    }    
    func (h *hellocontroller) lotsofreplies(in *hello.hellorequest, stream hello.hello_lotsofrepliesserver)  error {    
        for i := 0; i < 10; i++ {    
            stream.send(&hello.helloresponse{message : fmt.sprintf("%s %s %d", in.name, "reply", i)})    
        }    
        return nil    
    }

    // main.go    
    package main    
    import (    
        "log"    
        "net"    
        "hello/go_server/proto/hello"    
        "hello/go_server/controller/hello_controller"    
        "google.golang.org/grpc"    
    )    
    const (    
        address = "0.0.0.0:9090"    
    )    
    func main() {    
        listen, err := net.listen("tcp", address)    
        if err != nil {    
            log.fatalf("failed to listen: %v", err)    
        }    
        s := grpc.newserver()    
        // 服务注册    
        hello.registerhelloserver(s, &hello_controller.hellocontroller{})    
        log.println("listen on " + address)    
        if err := s.serve(listen); err != nil {    
            log.fatalf("failed to serve: %v", err)    
        }    
    }

 



运行:

 

  go run main.go    
    2019/07/28 17:51:20 listen on 0.0.0.0:9090

 


编写客户端请求接口的代码

  
 

package main   
import ( "hello/go_client/proto/hello" "io" "log" "golang.org/x/net/context" "google.golang.org/grpc" ) const ( // grpc 服务地址 address = "0.0.0.0:9090" ) func main() { conn, err := grpc.dial(address, grpc.withinsecure()) if err != nil { log.fatalln(err) } defer conn.close() // 初始化客户端 c := hello.newhelloclient(conn) // 调用 sayhello 方法 res, err := c.sayhello(context.background(), &hello.hellorequest{name: "hello world"}) if err != nil { log.fatalln(err) } log.println(res.message) // 调用 lotsofreplies 方法 stream, err := c.lotsofreplies(context.background(),&hello.hellorequest{name: "hello world"}) if err != nil { log.fatalln(err) } for { res, err := stream.recv() if err == io.eof { break } if err != nil { log.printf("stream.recv: %v", err) } log.printf("%s", res.message) } }

 



运行:

    go run main.go    
    2019/07/28 17:58:13 hello world    
    2019/07/28 17:58:13 hello world reply 0    
    2019/07/28 17:58:13 hello world reply 1    
    2019/07/28 17:58:13 hello world reply 2    
    2019/07/28 17:58:13 hello world reply 3    
    2019/07/28 17:58:13 hello world reply 4    
    2019/07/28 17:58:13 hello world reply 5    
    2019/07/28 17:58:13 hello world reply 6    
    2019/07/28 17:58:13 hello world reply 7    
    2019/07/28 17:58:13 hello world reply 8    

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网