go

grpc基本使用

2021-03-23  本文已影响0人  lesterhnu

前言

grpc 是一种基于 HTTP/2 设计的RPC框架,采用protobuf作为idl (交互式数据语言Interactive Data Language) 本篇简单介绍下grpc的使用,并制作一个demo

一、安装protoc

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

二、项目创建

1.创建目录结构

hello
├── client
│ └── client.go
└── server
└── server.go
└── proto
└── hello.proto
└── hello.pb.go # 通过protoc命令生成
├── go.mod

编写proto文件
// hello.proto
syntax = "proto3";
service HelloService {
    rpc SayHello(SayHelloRequest)returns(SayHelloResponse){}
}
message SayHelloRequest{
    string name = 1;
}
message SayHelloResponse {
    string msg = 1;
}
生成pb文件  proto/hello.pb.go
$ protoc --go_out=plugins=grpc:./ ./proto/hello.proto

2 编写服务端代码

// server/server.go
package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    hello "hello/proto"
    "log"
    "net"
)

type HelloServer struct {
}

func (h *HelloServer) SayHello(ctx context.Context, request *hello.SayHelloRequest) (*hello.SayHelloResponse, error) {
    name := request.Name
    fmt.Printf("receive name : %s", name)
    msg := fmt.Sprintf("hello, %s", name)
    return &hello.SayHelloResponse{Msg: msg}, nil
}
func main() {
    server  := grpc.NewServer() // 创建gRPC Server 对象
    // 将HelloService 注册到gRPC Server 的内部注册中心;接收到请求时,通过内部的服务发现,发现该服务的端口并转接进行逻辑处理
    hello.RegisterHelloServiceServer(server,&HelloServer{})
    // 创建listen,监听tcp端口
    lis, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatalf("failed to listen:%+v", err)
    }
    if err := server .Serve(lis); err != nil {
        log.Fatalf("err %+v", err)
    }
}

3 编写客户端代码

// client/client.go
package main

import (
    "context"
    "google.golang.org/grpc"
    hello "hello/proto"
    "log"
)

const (
    Address = "127.0.0.1:8080"
)

func main() {
    conn, err := grpc.Dial(Address, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    client := hello.NewHelloServiceClient(conn)
    ctx := context.Background()
    request := &hello.SayHelloRequest{Name: "lester"}
    response, err := client.SayHello(ctx, request)
    if err != nil {
        log.Fatalf("get response err :%v", err)
    }
    log.Printf("receive response msg:%s", response.Msg)
}

go run server/server.go
go run client/client.go

客户端输出结果


image.png
上一篇下一篇

猜你喜欢

热点阅读