dubbo icon indicating copy to clipboard operation
dubbo copied to clipboard

Consumer端异步回调缺少一个API 用于设置单次调用业务上下文

Open rhion opened this issue 10 years ago • 4 comments

<dubbo:method name="get" async="true" onreturn = "notify.onreturn" onthrow="notify.onthrow" />

在Consumer 请求服务时,需要一个类似 CallbackInvocationContext.setContext(bizObject); 可以设置一个业务对象(上下文)

当请求回调时,在业务notifyimpl 类如

@Override
    public void onreturn(Object arg) {
        //此处可以拿到业务调用上下文
          CallbackInvocationContext.getContext();
    }

//这里提供一个修改方案,未经验证。

新加类 CallbackInvocationContext 放入 dubbo.remoting

public class CallbackInvocationContext {
    private static ThreadLocal<Object> callbackContext = new ThreadLocal<Object>();

    public static void setContext(Object obj) {
        callbackContext.set(obj);
    }

    public static Object getContext() {
        return callbackContext.get();
    }
}

修改DefaultFuture 增加字段,并修改构造方法初始化此字段,修改请求返回代码 恢复CallbackInvocationContext

//业务调用上下文, 请求后可以在callback内通过CallbackInvocationContext拿到此值

  private volatile   Object bizContext ;

public DefaultFuture(Channel channel, Request request, int timeout){
        this.channel = channel;
        this.request = request;
        this.id = request.getId();
        this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
        // put into waiting map.
        FUTURES.put(id, this);
        CHANNELS.put(id, channel);
        //从请求线程获取上下文
        this.bizContext=CallbackInvocationContext.getContext();
    }
private void doReceived(Response res) {
        lock.lock();
        try {
            response = res;
            if (done != null) {
                done.signal();
            }
        } finally {
            lock.unlock();
        }
        if (callback != null) {
      //恢复业务请求上下文
          CallbackInvocationContext.setContext(this.bizContext)
          invokeCallback(callback);
        }
    }

rhion avatar Apr 07 '16 06:04 rhion

你的意思是从consumer透传对象到server端,server端也可以透传对象到comsumer端?

teaey avatar Apr 08 '16 15:04 teaey

不是透传对象。这个对象一直都在client端。只是需要从invoke线程 带到 dubbo的异步callback线程。 让callback线程,这样在callback线程执行业务代码时,业务代码可以根据invoke时的某些上线文做出一些动作,比如我在invoke时持有一个jetty的挂起动作,我可以在callback时继续用这个对象做jetty恢复。 我已经在阿里内部进行hack这个功能,测试通过了。只不过内部没有源码不知道怎么发布。 具体修改位置在dubbo.remoting jar

rhion avatar Apr 21 '16 06:04 rhion

牛牛牛。。

zouchunhui avatar Feb 22 '17 03:02 zouchunhui

支持,我也正想要这个功能呢

blackshadowwalker avatar Nov 15 '17 10:11 blackshadowwalker