Skip to content

Latest commit

 

History

History
210 lines (162 loc) · 5.1 KB

2016-10-31-grpc-101.md

File metadata and controls

210 lines (162 loc) · 5.1 KB
layout title date categories tags excerpt
post
Getting started with gRPC
2016-10-31 13:00:30 -0700
Distributed
gRPC
Getting started with gRPC

不知道从什么时候开始,使用gRPC成为编写C-S程序的新潮流,就连etcd v3也使用gRPC。

一方面,使用gRPC可以大大简化Client与Server的消息封装以及API的实现,这两者是非常琐碎的事情;另一方面,gRPC使用protobuf及HTTP2,性能相对于传统的JSON,性能有一些优势。

Install gRPC

Use the following command to install gRPC.

$ go version
go version go1.5.1 darwin/amd64
$ go get google.golang.org/grpc

Install Protocol Buffers v3 compiler, which is used to generate gRPC service code.

$ wget https://github.com/google/protobuf/releases/download/v3.1.0/protoc-3.1.0-osx-x86_64.zip
$ unzip protoc-3.1.0-osx-x86_64.zip
$ bin/protoc --version
libprotoc 3.1.0

Install the protoc plugin for Go.

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

Try helloworld

$ cd $GOPATH/src/google.golang.org/grpc/examples/helloworld

helloworld/helloworld.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";

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

Run server and client:

$ go run greeter_server/main.go

$ go run greeter_client/main.go
2016/10/31 20:12:27 Greeting: Hello world

Update gRPC service

helloworld/helloworld.proto增加SayHelloAgain方法:

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
...

生成新的helloworld/helloworld.pb.go:

$ protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld

Update the server:

greeter_server/main.go增加新的SayHelloAgain的实现:

package main

import (
    "log"
    "net"

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

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 (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello again " + 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{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

Update the client:

greeter_client/main.go增加对SayHelloAgain的调用:

import (
    "log"
    "os"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    pb "google.golang.org/grpc/examples/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)
    r, err = c.SayHelloAgain(context.Background(), &pb.HelloRequest{Name: name})
    if err != nil {
        log.Fatalf("could not greet: %v", err)
    }
    log.Printf("Greeting: %s", r.Message)

}

Run it:

$ go run greeter_client/main.go
2016/11/01 09:45:46 Greeting: Hello world
2016/11/01 09:45:46 Greeting: Hello again world

More