宝玛科技网
您的当前位置:首页java grpc threadlocal使用

java grpc threadlocal使用

来源:宝玛科技网

背景:在项目全文环境中获取公共数据 例如 当前用户的id等。

需要再 grpc 中 获取headers的信息然后设置到上下文对象 Context 中

  • 常量中定义需要公布的秘钥信息:
public class GrpcContextKey {
    public static final Context.Key<SecUser> USER_KEY = Context.key("USER");
}
  • 中设置绑定需要公布的信息:
  @Override
   public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
                                                                 Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        //获取客户端参数
        Metadata.Key<String> userKey= Metadata.Key.of("token", Metadata.ASCII_STRING_MARSHALLER);
        String userId= headers.get(userKey);
        Context ctx = Context.current().withValues(GrpcContextKey.USER_KEY, secUser, GrpcContextKey.TOKEN_KEY, userId);
        return Contexts.interceptCall(ctx, call, headers, next);
    }
  • 使用
GrpcContextKey .USER_KEY .get()

附赠:

  • springboot 整合:

  • 原理:

  • http2 GO AWAY (一段时间后channel状态 idle 问题):

因篇幅问题不能全部显示,请点此查看更多更全内容