美文网首页
demo系列Grpc

demo系列Grpc

作者: rushui | 来源:发表于2020-05-18 19:35 被阅读0次

准备工作

go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go
export PATH=$PATH:$GOPATH/bin

编辑pd/hello.proto

syntax = "proto3";

option objc_class_prefix = "HLW";

package hello;

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

server.go

package main

import (
    "log"
    "net"

    pb "github.com/grpc-example/simple/pb"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

const (
    PORT = ":50001"
)

type server struct{}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    log.Println("request: ", in.Name)
    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()
    grpc.EnableTracing = true
    pb.RegisterGreeterServer(s, &server{})
    log.Println("rpc服务已经开启")
    s.Serve(lis)
}

cli.go

package main

import (
    "log"
    "os"

    pb "github.com/grpc-example/simple/pb"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

const (
    address = "localhost:50001"
)

func main() {
    conn, err := grpc.Dial(address, grpc.WithInsecure())

    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }

    defer conn.Close()

    c := pb.NewGreeterClient(conn)

    name := "lin"
    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.Println(r.Message)
}

编译.proto文件命令

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

下载demo

git clone https://github.com/grpc-example/simple.git
cd simple

run server

go run server.go

run client

go run cli.go

项目地址

https://github.com/grpc-example/simple

相关文章

网友评论

      本文标题:demo系列Grpc

      本文链接:https://www.haomeiwen.com/subject/pvmuohtx.html