dubbo中如何传递隐式参数

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服务就会拿不到参数。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

《小书生》

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值