背景:在项目全文环境中获取公共数据 例如 当前用户的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 问题):
这个 问题我们是用心跳链接解决的 暂时没有想到别的办法,有解决方案的欢迎及时指正,一定有解决办法的