GRPC微服务入门 | 青训营

206 阅读2分钟

IDL(Interface description Language)文件:通过一种中立的方式来描述接口,使得在不同平台上的不同的对象和不同语言编写的程序可以互相通信。

下面使用proto作为IDL文件。

1.proto文件规则

 syntax="proto3";
 ​
 package idl;
 ​
 option go_package = "./idl/my_proto;student_service";
 ​
 import "google/protobuf/timestamp.proto";
 message Student {   
   string name = 1;  
   repeated string Location = 4; 
   map<string,float> Scores = 3;
   bool Gender = 5;
   int32 Age = 6;
   float Height = 7;
   google.protobuf.Timestamp Birthday = 8;
 }
 ​
 message Request {
   string studentId = 1;
 }
 ​
 service StudentService {
   rpc GetStudentInfo (Request) returns (Student);
 }

这段代码是关于使用GRPC进行微服务开发的。逐行解释其内容:

  1. syntax = "proto3";:指定采用Protocol Buffers V3版本的语法编写。
  2. package idl;:类似于Go语言中的包功能,用来组织代码文件。
  3. option go_package = "./idl/my_proto;student_service";:设置生成的Go文件的路径和包名。路径前面的.表示基准地址,与命令行中的--go_out指定的路径共同生成最终的Go文件地址。
  4. import "google/protobuf/timestamp.proto";:导入其他Proto文件,根据需要引用其中的定义。
  5. message Student { ... }:定义了一个消息类型(类似于Go语言的struct),用来描述学生信息。其中包括了学生的姓名、位置(可重复)、分数(映射类型)、性别、年龄、身高和生日(使用了Google的Timestamp类型)。
  6. message Request { ... }:定义了另一个消息类型,用于请求学生信息时发送学生ID。
  7. service StudentService { ... }:定义了一个服务接口(类似于Go语言的接口),其中可以定义多个函数。这里定义了一个函数GetStudentInfo,它接收一个Request类型的参数,并返回一个Student类型的结果。

通过以下命令(之一)把proto文件转为go文件:

 protoc --go_out=plugins=grpc:. --proto_path=./idl -I=./idl/third_proto student_service.proto    #go_out
 protoc --gogofaster_out=plugins=grpc:. --proto_path=./idl -I=./idl/third_proto student_service.proto #gogofaster_out
  • go_out可以换成中的go可以换成gogofaster等其它指令
  • grpc:.中的.表示基准地址,与文件中的go_package路径共同生成go文件的最终地址。
  • proto_path用于指定原始的输入文件在哪个目录下
  • -I用于指定引用的proto文件所在路径,再从文件中的import路径来共同引用到那个proto文件。

2.实现proto生成的接口并注册服务

在proto文件中定义了GetStudentInfo接口,你需要在自己的go文件中实现它。

  • 定义一个结构体(可以是空的,只要能实现接口即可)

  • 利用这个结构体去实现接口

    • 入参增加一个context
    • 出参增加一个error
  • Register这个接口(通过结构体类型来找到其成员函数(地址))