go grpc 学习笔记

874 阅读2分钟
1. grpc

gRPC 是一个高性能、开源和通用的 RPC 框架 。

gRPC 一开始由 google 开发,是一款语言中立、平台中立、开源的远程过程调用(RPC)系统。

gRPC 默认使用 protocol buffers,这是 Google 开源的一套成熟的结构数据序列化机制(当然也可以使用其他数据格式如 JSON)。

2. 开发环境准备

proto文件编译器下载。

下载地址: github.com/protocolbuf…

选择适合自己系统的版本安装。(windows 需要配置环境变量)

使用 protoc --version 检查是否安装完成。

proto 工具包 获取

go get -u github.com/golang/protobuf/proto

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

grpc 获取

go get -u google.golang.org/grpc

3.proto文件编写
//使用 proto3 
syntax="proto3";
//包名
package proto;
//定义请求
message BookRequest{
    string BookName=1;
}
//定义返回
message BookResponse{
    int32 ID=1;
    string BookName=2;
    float Price=3;
}
//服务
service BookService{
	//定义方法
    rpc GetBookInfo (BookRequest) returns (BookResponse);
}

执行命令: protoc --go_out=plugins=grpc:. book.proto ,会自动生成文件 book.pb.go。

4.grpc服务器端代码

编写服务器端的代码步骤

  1. 服务器端应该先监听某个端口。
  2. 实例化 grpc 。
  3. 在 grpc 上注册服务。
  4. 启动服务端

代码 demo

(rpc_three/proto 是本地的包)

package main

import (
	"context"
	"net"
	"rpc_three/proto"

	"google.golang.org/grpc"
)

//Bookservice Bookservice
type Bookservice struct{}

//GetBookInfo GetBookInfo
func (b *Bookservice) GetBookInfo(ct context.Context, req *proto.BookRequest) (*proto.BookResponse, error) {
	return &proto.BookResponse{
		ID:       1,
		BookName: req.BookName,
		Price:    23.33,
	}, nil
}

func main() {
    //使用 net 监听端口
	lis, err := net.Listen("tcp", ":8081")
	if err != nil {
		return
	}
    //实例化grpc
	s := grpc.NewServer()
    //注册服务
	proto.RegisterBookServiceServer(s, new(Bookservice))
    //启动服务器
	s.Serve(lis)

}

上面的代码中需要实现的接口 GetBookInfo 可以在生成的文件 book.pb.go 中看到,我们可以抄里面的代码,写起来会方便些。

// BookServiceServer is the server API for BookService service.
type BookServiceServer interface {
	GetBookInfo(context.Context, *BookRequest) (*BookResponse, error)
}

RegisterBookServiceServer 方法也可以在文件中找到。

func RegisterBookServiceServer(s *grpc.Server, srv BookServiceServer) {
	s.RegisterService(&_BookService_serviceDesc, srv)
}
5.grpc客户端代码

编写客户端的代码

  1. 连接服务端。
  2. 启动grpc客户端。
  3. 调用方法。

代码 demo

(rpc_three/proto 是本地的包)

package main

import (
	"context"
	"fmt"
	"rpc_three/proto"

	"google.golang.org/grpc"
)

func main() {
    //连接
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()
    //实例化
	c := proto.NewBookServiceClient(conn)
    //调用接口
	r, _ := c.GetBookInfo(context.Background(), &proto.BookRequest{BookName: "golang"})
	fmt.Printf("r:%v", r)

}