golang grpc demo

1.grpm 安装:

git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc

2.proto, protoc-gen-go 安装:

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

3.protoc 安装:

git clone https://github.com/protocolbuffers/protobuf.git
cd $GOPATH/src/github.com/protocolbuffers/
./autogen.sh
./configure
make -j12
make install

4.go-genproto 安装(运行时需要的依赖,下载完移动到相应的目录里面)

git https://github.com/googleapis/go-genproto.git

5.protoc 查看版本:

[root@wangjq]# protoc --version
libprotoc 3.10.0

 6.目录结构:

[root@wangjq demo]# tree
.
├── client
│   └── main.go
├── example
│   └── data.proto
└── server
    └── main.go

3 directories, 4 files

7.data.proto 内容如下

syntax = "proto3"; //指定proto版本

package proto;

//定义请求结构
message HelloRequest{
    string name=1;
}

//定义响应结构
message HelloReply{
    string message=1;
}

//定义Hello服务
service Hello{
    //定义服务中的方法
    rpc SayHello(HelloRequest) returns (HelloReply){}
}

8.生成 data.pb.go 文件

protoc -I . --go_out=plugins=grpc:. ./data.proto 

9.服务端代码

package main

import (
    pb "demo/example"
    "fmt"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "net"
)

const (
    //gRPC服务地址
    Address = "127.0.0.1:50052"
)

//定义一个helloServer并实现约定的接口
type helloService struct{}

func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    resp := new(pb.HelloReply)
    resp.Message = "hello" + in.Name + "." 
    return resp, nil 
}

var HelloServer = helloService{}

func main() {
    listen, err := net.Listen("tcp", Address)
    if err != nil {
        fmt.Printf("failed to listen:%v", err)
    }

    //实现gRPC Server
    s := grpc.NewServer()
    //注册helloServer为客户端提供服务
    pb.RegisterHelloServer(s, HelloServer) //内部调用了s.RegisterServer()
    fmt.Println("Listen on" + Address)

    s.Serve(listen)
}

10.客户端代码

package main

import (
    pb "demo/example"
    "fmt"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

const (
    Address = "127.0.0.1:50052"
)

func main() {
    //连接gRPC服务器
    conn, err := grpc.Dial(Address, grpc.WithInsecure())
    if err != nil {
        fmt.Println(err)
    }   
    defer conn.Close()

    //初始化客户端
    c := pb.NewHelloClient(conn)

    //调用方法
    reqBody := new(pb.HelloRequest)
    reqBody.Name = "gRPC"
    r, err := c.SayHello(context.Background(), reqBody)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(r.Message)
}

11.运行测试

服务端运行:
[root@wangjq demo]# go run server/main.go 
Listen on127.0.0.1:50052

客户端运行:
[root@wangjq demo]# go run client/main.go 
hellogRPC.

 

posted @ 2019-09-23 14:40  salami_china  阅读(1801)  评论(0编辑  收藏  举报