rpc

package
v1.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2026 License: MIT Imports: 10 Imported by: 0

README

RPC

rpc 包提供了标准化的 RPC 调用封装与响应处理工具。

设计理念

本包旨在统一处理微服务间的响应格式,遵循 Code/Message/Data 模式:

  • Code:业务状态码(200 表示成功)。
  • Message:业务提示信息。
  • Data:实际业务数据。

核心功能

WithRemoteInvoke

泛型函数,用于发起远程调用并自动处理响应解包。

处理逻辑

  1. 网络错误:直接返回 error
  2. Nil 检查:防御性处理“带类型的 nil”。
  3. 业务错误:若 Code != 200,提取 Message 并封装为 error 返回。
  4. 成功:仅返回 Data 部分。

使用示例

假设 Proto 定义如下:

message GetUserResponse {
    uint32 code = 1;
    string message = 2;
    User data = 3;
}

调用代码:

import "github.com/fireflycore/go-micro/rpc"

// T:业务数据类型(pb.User)
// R:响应类型(*pb.GetUserResponse),需实现 rpc.RemoteResponse[pb.User]
user, err := rpc.WithRemoteInvoke[pb.User, *pb.GetUserResponse](func() (*pb.GetUserResponse, error) {
	return client.GetUser(ctx, &pb.GetUserRequest{Id: 1})
})

if err != nil {
	// 处理网络错误或业务错误(Code != 200)
	return err
}

// 直接使用 user 对象
fmt.Println(user.Name)

Documentation

Overview

Package rpc 提供标准化的 RPC 调用封装与响应处理工具。

Index

Constants

View Source
const MetaKeyParseErrorFormat = "%s 解析失败"

MetaKeyParseErrorFormat 用于构造元信息缺失/解析失败的错误文本。

Variables

View Source
var (
	// ErrRemoteResponseIsNil 表示远程调用返回的响应对象为空。
	ErrRemoteResponseIsNil = errors.New("远程响应为空")
	// ErrRemoteCallFailed 表示远程调用失败但未返回可读错误信息。
	ErrRemoteCallFailed = errors.New("远程调用失败")
)

Functions

func NewRemoteServiceGrpcClient added in v0.9.8

func NewRemoteServiceGrpcClient(bootstrapConf conf.BootstrapConf) (*grpc.ClientConn, error)

func ParseMetaKey

func ParseMetaKey(md metadata.MD, key string) (string, error)

ParseMetaKey 解析元信息 key。

Types

type ServiceContext added in v1.1.2

type ServiceContext struct {
	// contains filtered or unexported fields
}

ServiceContext 持有服务级别的静态元信息,用于构造服务间调用的出站上下文。 应在服务启动时初始化一次,作为单例注入或封装进中间件使用。

func NewServiceContext added in v1.1.2

func NewServiceContext(bootstrapConf conf.BootstrapConf) *ServiceContext

NewServiceContext 初始化服务上下文。 基于启动配置构建服务级别的静态 metadata,后续每次远程调用都会以此为基础进行扩展。

func (*ServiceContext) BuildServiceMetadata added in v1.1.6

func (sc *ServiceContext) BuildServiceMetadata() metadata.MD

BuildServiceMetadata 构建服务级别的静态元信息。

func (*ServiceContext) GetMetadata added in v1.1.3

func (sc *ServiceContext) GetMetadata() metadata.MD

GetMetadata 返回服务静态元信息的副本。

func (*ServiceContext) InjectTrace added in v1.1.2

func (sc *ServiceContext) InjectTrace(md metadata.MD) metadata.MD

InjectTrace 将链路追踪字段注入 metadata,维护 TraceId -> ParentId -> SpanId 的调用链层级。

规则:

  • TraceId:有则继承(保持链路唯一性),无则新建(标识链路起点)
  • ParentId:将上游的 SpanId 记录为本跳的 ParentId,构建调用树
  • SpanId:每次调用都生成新值,唯一标识当前这一跳

func (*ServiceContext) MergeServiceMetadata added in v1.1.6

func (sc *ServiceContext) MergeServiceMetadata(md metadata.MD) metadata.MD

MergeServiceMetadata 将本服务的静态元信息合并进目标 md。 RouteMethod 已存在时不覆盖,其余字段一律以服务静态值为准。

func (*ServiceContext) NewOutgoingContext added in v1.1.6

func (sc *ServiceContext) NewOutgoingContext(md metadata.MD, timeout time.Duration) (context.Context, context.CancelFunc)

NewOutgoingContext 将 metadata 写入新的出站上下文,并附加超时控制。

func (*ServiceContext) WithExternalContext added in v1.1.6

func (sc *ServiceContext) WithExternalContext(md metadata.MD, timeout time.Duration) (context.Context, context.CancelFunc)

WithExternalContext 将外部传入的 metadata 与本服务静态元信息合并,构造出站上下文。

适用场景:

  • 处理来自消息队列、Webhook 等非 gRPC 入口的请求,已有部分上下文信息需要透传
  • 由外部系统注入初始 metadata,服务侧补全自身身份信息后继续向下游调用

行为说明:

  • 以传入的 md 为基础,本服务静态元信息作为补充(RouteMethod 不覆盖)
  • 自动注入新的 TraceId(若不存在)和 SpanId,维护链路连续性
  • 生命周期由 timeout 独立控制,与调用方上下文无关

func (*ServiceContext) WithInheritContext added in v1.1.2

func (sc *ServiceContext) WithInheritContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

WithInheritContext 在父上下文的基础上,创建携带完整链路信息的出站上下文。

适用场景:

  • 处理用户请求时,服务需要继续调用下游服务
  • 需要保持 trace 链路连续,并透传用户身份

行为说明:

  • 基于 context.Background() 创建,生命周期由 timeout 独立控制,不受父上下文取消影响
  • 继承父上下文中的 TraceId,更新 SpanId 并将原 SpanId 设为 ParentId
  • 透传父上下文中的用户信息(UserId / AppId / TenantId)
  • 合并本服务的静态元信息,下游可据此识别直接调用方

func (*ServiceContext) WithPureContext added in v1.1.2

func (sc *ServiceContext) WithPureContext(timeout time.Duration) (context.Context, context.CancelFunc)

WithPureContext 创建一个与调用方请求完全隔离的纯净出站上下文。

适用场景:

  • 定时任务、事件驱动等服务主动发起的后台调用
  • 无需透传用户身份的内部服务调用

行为说明:

  • 基于 context.Background() 创建,调用方的取消信号不会传播,生命周期由 timeout 独立控制
  • 不携带用户信息(UserId / AppId / TenantId)
  • 自动生成全新的 TraceId 和 SpanId,作为新链路的起点

type UserContextMeta

type UserContextMeta struct {
	Session  string `json:"session"`
	ClientIp string `json:"client_ip"`

	UserId   string `json:"user_id"`
	AppId    string `json:"app_id"`
	TenantId string `json:"tenant_id"`

	RoleIds []string `json:"role_ids"`
	OrgIds  []string `json:"org_ids"`
}

UserContextMeta 表示用户元信息

func ParseUserContextMeta

func ParseUserContextMeta(md metadata.MD) (raw *UserContextMeta, err error)

ParseUserContextMeta 解析用户上下文元信息。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL