1.在dubbo服务调用中,使用ThreadLocal是无法进行ThreadLoca对象传递的,即使使用InheritableThreadLocal父子线程传递依然无法进行传递,这个时候公共参数就没法通过线程对象进行传递,这个时候可以使用dubbo RpcContext进行参数隐式传递。
@Component
@Slf4j
public class TokenHandler implements HandlerInterceptor {
@Reference
private ZcLoginService zcLoginService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object)throws Exception{
String token = httpServletRequest.getHeader("tokenId");
log.info("=====================================请求token:{}",token);
if(StringUtils.isEmpty(token)){
throw new TokenException("用户token不存在,请重新登陆");
}
//校验token真实性
ResponseData<Customer> responseData = zcLoginService.findToken(token);
log.info("解析后的token:{}",JSON.toJSONString(responseData));
if (!ExceptionEnum.SUCCESS.getCode().equals(responseData.getCode())){
throw new TokenException(responseData.getCode(),responseData.getMessage());
}
Map map = new HashMap();
map.put("userKey", "userValue");
RpcContext.getContext().setAttachments(map);
return true;
}
}
@Override
public IdentifyRiskBookRsp queryIdentifyRiskBookByFlowId(IdentifyReq record) {
System.out.println(" RpcContext.getContext().get(userKey);"+ RpcContext.getContext().getAttachments());
}
2.在每一次Protocol层消费者调用过程中,会依次调用ConsumerContextFilter的invoke方法、FutureFilter的invoke方法、MonitorFilter中的invoke⽅法,最后会调到DubboInvoker中invoke⽅法。这里只看ConsumerContextFilter的invoke方法,如下:
@Activate(group = Constants.CONSUMER, order = -10000)
public class ConsumerContextFilter implements Filter {
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
RpcContext.getContext()
.setInvoker(invoker)
.setInvocation(invocation)
.setLocalAddress(NetUtils.getLocalHost(), 0)
.setRemoteAddress(invoker.getUrl().getHost(),
invoker.getUrl().getPort());
if (invocation instanceof RpcInvocation) {
((RpcInvocation)invocation).setInvoker(invoker);
}
try {
return invoker.invoke(invocation);
} finally {
RpcContext.getContext().clearAttachments();
}
}
}
上述源码知每一次dubbo接口调用结束后都会清除RpcContext的attachments,如果A-B-C,在B服务取出后,到C服务就会拿不到参数。