gRPC(可选)
gRPC 运行时
xGrpcRunner.New 将 gRPC 服务挂载到 xMain.Runner 生命周期中
gRPC 运行时
xGrpcRunner 提供 gRPC 服务的启动与优雅退出能力,可直接作为 xMain.Runner 的附加协程使用。
import xGrpcRunner "github.com/bamboo-services/bamboo-base-go/plugins/grpc/runner"核心入口
func New(options ...Option) func(ctx context.Context, option ...any)返回值可直接传给:
xMain.Runner(reg, log, registerRoute, grpcTask)常用 Option
字段
类型
集成示例
package main
import (
"context"
"time"
xLog "github.com/bamboo-services/bamboo-base-go/common/log"
xMain "github.com/bamboo-services/bamboo-base-go/major/main"
xReg "github.com/bamboo-services/bamboo-base-go/major/register"
xGrpcIUnary "github.com/bamboo-services/bamboo-base-go/plugins/grpc/interceptor/unary"
xGrpcRunner "github.com/bamboo-services/bamboo-base-go/plugins/grpc/runner"
"google.golang.org/grpc"
)
func main() {
reg := xReg.Register(context.Background(), nil)
log := xLog.WithName(xLog.NamedMAIN)
grpcTask := xGrpcRunner.New(
xGrpcRunner.WithLogger(xLog.WithName(xLog.NamedGRPC)),
xGrpcRunner.WithGracefulStopTimeout(30*time.Second),
xGrpcRunner.WithRegisterService(func(ctx context.Context, server grpc.ServiceRegistrar) {
// 在这里注册你的服务:
// pb.RegisterYourServiceServer(server, yourHandler)
}),
xGrpcRunner.WithUnaryInterceptors(
xGrpcIUnary.InitContext(reg.Init.Ctx),
xGrpcIUnary.ResponseBuilder(),
),
)
xMain.Runner(reg, log, registerRoute, grpcTask)
}内置行为
- 默认使用
GRPC_PORT(默认1119)作为监听端口。 - 默认启用追踪拦截器
Trace(复用或生成x_request_uuid)。 - 由
xMain.Runner统一管理退出信号:SIGINT/SIGTERM。 GRPC_REFLECTION=true时启用反射。
拦截器链路
默认链路中已包含 Trace()。你可以通过 WithUnaryInterceptors(...) 追加内置拦截器:
xGrpcRunner.WithUnaryInterceptors(
xGrpcIUnary.InitContext(reg.Init.Ctx),
xGrpcIUnary.Recover(),
xGrpcIUnary.Middleware(), // 服务级中间件分发
xGrpcIUnary.ResponseBuilder(), // 放在最后
)完整链路顺序:
Trace()(Runner 默认)InitContext(...)(你追加)Recover()(你追加)Middleware()(你追加)- 服务级中间件链(若有)
ResponseBuilder()(你追加)- 业务 Handler
流式拦截器
如需使用流式 RPC,可通过 WithStreamInterceptors 追加流式拦截器:
import xGrpcIStream "github.com/bamboo-services/bamboo-base-go/plugins/grpc/interceptor/stream"
xGrpcRunner.WithStreamInterceptors(
xGrpcIStream.InitContext(reg.Init.Ctx),
xGrpcIStream.Recover(),
xGrpcIStream.Middleware(),
)流式拦截器没有
ResponseBuilder,因为流式响应由业务代码直接控制。
错误处理
xGrpcRunner 配合 ResponseBuilder 拦截器与 xError 使用。业务 handler 直接返回 *xError.Error,ResponseBuilder 自动将其映射为标准 gRPC status 返回给客户端。
详见 内置拦截器 中的 ResponseBuilder 章节。