返回

用 gRPC 编写微服务:小白指南

后端

引言

gRPC(g RPC r emote p rocedure c all)是一个高性能远程过程调用框架,最初由 Google 开发,用于在其广泛分布式系统中实现微服务。它已成为开发分布式系统的流行选择,因为它提供了强大的功能、效率和灵活性。

安装和设置

要开始使用 gRPC,您需要安装 Protocol Buffers (Protobuf) 编译器和 gRPC 工具。请遵循以下步骤:

  1. 安装 Protocol Buffers 编译器: 转到 https://github.com/protocolbuffers/protobuf/releases,下载最新版本的 protobuf 编译器并按照说明进行安装。
  2. 安装 gRPC 工具: 转到 https://grpc.io/docs/languages/go/,下载并安装 gRPC 工具。

定义 Protobuf 服务

Protobuf 服务定义在 .proto 文件中。这是一个简单的示例:

syntax = "proto3";

package helloworld;

service Greeter {
  rpc SayHello(HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

生成代码

使用 protoc 编译器从 .proto 文件生成代码:

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

这将在当前目录中生成 helloworld.pb.gohelloworld_grpc.pb.go 文件。

实现服务端

main.go 文件中实现服务端:

package main

import (
    "context"
    "fmt"

    helloworld "github.com/grpc-example/helloworld/helloworldpb"
)

type server struct {}

func (s *server) SayHello(ctx context.Context, req *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
    return &helloworld.HelloReply{
        Message: "Hello " + req.GetName() + "!",
    }, nil
}

func main() {
    lis, err := net.Listen("tcp", ":9090")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    s := grpc.NewServer()
    helloworld.RegisterGreeterServer(s, &server{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

实现客户端

client.go 文件中实现客户端:

package main

import (
    "context"
    "fmt"

    helloworld "github.com/grpc-example/helloworld/helloworldpb"
    "google.golang.org/grpc"
)

func main() {
    conn, err := grpc.Dial("localhost:9090", grpc.WithInsecure())
    if err != nil {
        log.Fatalf("failed to dial: %v", err)
    }
    defer conn.Close()

    client := helloworld.NewGreeterClient(conn)
    req := &helloworld.HelloRequest{
        Name: "John",
    }
    res, err := client.SayHello(context.Background(), req)
    if err != nil {
        log.Fatalf("failed to say hello: %v", err)
    }
    fmt.Println(res.GetMessage())
}

运行服务和客户端

  1. 在一个终端中运行服务端:go run main.go
  2. 在另一个终端中运行客户端:go run client.go

结论

这篇文章提供了一个简单的入门教程,介绍了如何使用 gRPC 编写微服务。通过遵循这些步骤,您将能够为自己的项目创建和使用 gRPC 服务。