Go中实现gRPC

简介

gRPCgoogle开发的远程过程调用系统,基于 http2.0协议标准开发,编码协议使用 protobuf

编写proto

实现一个计算两个数之和的服务。

syntax = "proto3";

package proto;

option go_package = "/cal;cal";

message RequestInfo {
  int64 number1 = 1;
  int64 number2 = 2;
}

message ResponseInfo {
  int64 res = 1;
}

service Cal {
  rpc Add (RequestInfo) returns (ResponseInfo) {}
}

生成go文件

使用 protoc生成 go文件。

protoc --go_out=. --go-grpc_out=. ./proto/cal.proto

生成 cal.pb.gocal_grpc.pb.go两个文件。

cal.pb.go文件中主要包含 proto中的 message结构体。

cal_grpc.pb.go文件中包含注册服务端的方法 RegisterCalServer、实例化客户端的方法 NewCalClient、未实现服务的结构体 UnimplementedCalServer

编写服务端

package main

import (
    "context"
    "google.golang.org/grpc"
    "net"
    "test/cal"
)

type Cal struct {
    cal.UnimplementedCalServer
}

// 实现Add方法
func (c *Cal) Add(ctx context.Context, req *cal.RequestInfo) (res *cal.ResponseInfo, err error) {
    return &cal.ResponseInfo{Res: req.Number1 + req.Number2}, nil
}

func main() {
    // 监听
    listen, _ := net.Listen("tcp", ":8080")

    // 实例化grpc服务
    s := grpc.NewServer()

    // 注册服务
    cal.RegisterCalServer(s, &Cal{})

    // 启动
    s.Serve(listen)
}
  1. 结构体需包含 cal.UnimplementedCalServer
  2. 需实现 Add方法,如未实现会调用 cal.UnimplementedCalServer中的 Add方法。

编写客户端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
    "test/cal"
)

func main() {
    // 建立连接
    conn, _ := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))

    // 实例化客户端
    client := cal.NewCalClient(conn)

    // 调用服务
    res, _ := client.Add(context.Background(), &cal.RequestInfo{
        Number1: 1,
        Number2: 2,
    })

    fmt.Println(res)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!