You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在微服务任意位置访问gRPC拦截器中的请求元数据

gRPC服务端拦截器中Metadata的上下文传递与全局访问方案

1. 定义gRPC Context的存取Key

gRPC的Context通过唯一Key来存取数据,先定义静态Key用于存储请求头信息(可选择存整个Metadata或单独字段,这里提供两种方式):

import io.grpc.Context;
import io.grpc.Metadata;

public class GrpcContextKeys {
    // 存储完整请求Metadata的Key
    public static final Context.Key<Metadata> METADATA_KEY = Context.key("grpc-request-metadata");
    // 单独存储Accept-Country字段的Key
    public static final Context.Key<String> ACCEPT_COUNTRY_KEY = Context.key("accept-country");
}

2. 修改拦截器,将Metadata存入Context并传递

更新你的ServerSideInterceptor,从请求头提取需要的信息,存入新的Context后传递给后续调用链:

@Slf4j
@GrpcGlobalServerInterceptor
public class ServerSideInterceptor implements ServerInterceptor {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
                                                                 final Metadata headers,
                                                                 final ServerCallHandler<ReqT, RespT> next) {

        log.info("Setting user context, metadata {}", headers);

        // 从Metadata提取Accept-Country(gRPC默认将请求头键转为小写)
        String acceptCountry = headers.get(Metadata.Key.of("accept-country", Metadata.ASCII_STRING_MARSHALLER));
        
        // 创建携带数据的新Context
        Context newContext = Context.current()
                .withValue(GrpcContextKeys.METADATA_KEY, headers)
                .withValue(GrpcContextKeys.ACCEPT_COUNTRY_KEY, acceptCountry);

        // 用新Context拦截调用,传递上下文
        return Contexts.interceptCall(newContext, call, headers, next);
    }
}

注意:gRPC会自动将请求头的键转为小写,所以提取时要使用accept-country而非Accept-Country。

3. 在服务类或任意组件中访问Context数据

只要处于gRPC请求的处理线程链中,就能直接从Context中取出数据完成校验或业务逻辑:

示例1:在gRPC服务实现类中校验

import org.springframework.util.StringUtils;
import org.springframework.http.HttpStatus;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;

public class YourGrpcServiceImpl extends YourGrpcServiceGrpc.YourGrpcServiceImplBase {
    @Override
    public void yourRpcMethod(YourRequest request, StreamObserver<YourResponse> responseObserver) {
        // 从Context获取Accept-Country
        String country = GrpcContextKeys.ACCEPT_COUNTRY_KEY.get(Context.current());
        
        // 执行校验逻辑
        if(StringUtils.isEmpty(country)){
            ResponseWrapper errorResp = ResponseWrapper.builder()
                    .code(HttpStatus.BAD_REQUEST.value())
                    .message("Please provide 'Accept-Country' header")
                    .build();
            // 返回gRPC错误响应
            responseObserver.onError(Status.INVALID_ARGUMENT.withDescription(errorResp.getMessage()).asRuntimeException());
            return;
        }

        // 校验通过,执行业务逻辑
        // ...
        responseObserver.onNext(yourResponse);
        responseObserver.onCompleted();
    }
}

示例2:在普通Spring组件中访问

import org.springframework.stereotype.Component;

@Component
public class SomeBusinessService {
    public void doBusinessLogic() {
        // 从Context获取完整Metadata
        Metadata metadata = GrpcContextKeys.METADATA_KEY.get(Context.current());
        if(metadata != null) {
            String country = metadata.get(Metadata.Key.of("accept-country", Metadata.ASCII_STRING_MARSHALLER));
            // 基于country做业务处理
        }
    }
}

关键说明

  • gRPC的Context是线程绑定的,只要在处理gRPC请求的线程链中,无需手动传递就能获取上下文数据。
  • 可根据需求选择存储完整Metadata或单独字段,后者能减少不必要的数据读取。

内容的提问来源于stack exchange,提问作者justrying

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:20:04