进阶 www.iris-go.com 2026-10-20 02:39:14 · 19 阅读

第17章 Iris 框架集成 gRPC 实现 HTTP 与 RPC 服务双栈开发

gRPC 是一个现代开源的高性能远程过程调用(RPC)框架,适用于各种环境。它能在数据中心内部和跨数据中心之间高效连接服务,并支持负载均衡、链路追踪、健康检查和认证等插件化功能。它同样适用于分布式计算的终端环节,用于连接设备、移动应用和浏览器与后端服务。 Iris 与 gRPC 的集成位于 mvc 包中。 你曾经是否遇到将应用程序或其部分从 HTTP 转换为 gRPC 的困难?或者你希望自己的 gRPC 服务也能获得良好的 HTTP 框架支持?现在,使用 Iris,你可以兼得两者之长。只需通过控制器(你的服务结构体值)将它们注册为 Iris HTTP 路由,即可在不修改现有 gRPC 服务代码的情况下实现这一目标。 了解更多关于我们的讨论:https://github.com/kataras/iris/issues/1449#issuecomment-623260695 分步指南 我们将跟随官方的 helloworld gRPC 示例进行演示。如果你已经有处理 gRPC 服务的经验,可以跳过步骤 1 到 5。 1. 编写请求和响应的 proto schema。 text syntax = "proto3"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; } 2. 安装 protoc 的 Go 插件。 bash $ go get -u github.com/golang/protobuf/protoc-gen-go 3. 根据上述 helloworld.proto 文件生成 Go 文件。 bash $ protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld 4. 像往常一样实现 gRPC 服务,无论是否使用 Iris。 go import ( // [...] pb "myapp/helloworld" "context" ) go type Greeter struct { } // SayHello implements helloworld.GreeterServer. func (c *Greeter) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil } Iris 会自动将标准的 context.Context 绑定到 iris.Context.Request().Context(),而其他无法映射到已注册依赖的结构体则作为请求负载处理(取决于请求类型),例如 XML、YAML、Query、Form、JSON、Protobuf。 5. 将服务注册到 gRPC server go import ( // [...] pb "myapp/helloworld" "google.golang.org/grpc" ) 1
2
3
4
5
go grpcServer := grpc.NewServer() myService := &Greeter{} pb.RegisterGreeterServer(grpcServer, myService) 1
2
3
4
6. 将 myService 注册到 Iris mvc.New(party).Handle(ctrl, mvc.GRPC{...}) 选项支持按 Party 注册 gRPC 服务(无需完整包装),还可以选择只允许 gRPC 客户端访问。 为 gRPC 服务注册 MVC 应用控制器。只要 ServiceName 不同,就可以在同一个 Party 或应用中绑定任意多个 mvc gRPC 服务。 go import ( // [...] "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" ) 1
2
3
4
5
go app := iris.New() rootApp := mvc.New(app) rootApp.Handle(myService, mvc.GRPC{ Server: grpcServer, // 必填 ServiceName: "helloworld.Greeter", // 必填 Strict: false, }) 1
2
3
4
5
6
7
8
7. 生成 TLS 密钥 Iris 服务器需要运行在 TLS 下(这是 gRPC 的要求)。 bash $ openssl genrsa -out server.key 2048 $ openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650 1
2
8. 监听并启动服务 go app.Run(iris.TLS(":443", "server.crt", "server.key")) 1
发送 POST 请求到 https://localhost:443/helloworld.Greeter/SayHello,请求数据为 {"name": "John"},预期输出:{"message": "Hello John"}。 HTTP 客户端和 gRPC 客户端都可以与我们的 Iris+gRPC 服务通信。 练习文件 完整的服务端、客户端及测试代码见:https://github.com/kataras/iris/tree/main/_examples/mvc/grpc-compatible。

评论 (0)