Search in sources :

Example 6 with BoltSendableResponseCallback

use of com.alipay.sofa.rpc.message.bolt.BoltSendableResponseCallback in project sofa-rpc by sofastack.

the class BAsyncChainSampleServiceImpl method hello.

@Override
public String hello() {
    RpcInvokeContext context = RpcInvokeContext.getContext();
    LOGGER.info("--b1---:" + context);
    // 读取一定要在这里读取
    reqBaggage = context.getRequestBaggage("reqBaggageB");
    context.putResponseBaggage("respBaggageB_useful1", "在返A之前写入有用");
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        RpcInvokeContext.getContext().setResponseCallback(new BoltSendableResponseCallback() {

            @Override
            public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
                // 返回一定要写在这里
                RpcInvokeContext context = RpcInvokeContext.getContext();
                LOGGER.info("--b3---:" + context);
                if (reqBaggage != null) {
                    context.putResponseBaggage("respBaggageB", "b2aaa");
                } else {
                    context.putResponseBaggage("respBaggageB_force", "b2aaaff");
                }
                String s1 = (String) appResponse;
                // 这里已经取不到值了
                String reqBaggageD = context.getRequestBaggage("reqBaggageD");
                LOGGER.info("----reqBaggageD---:" + reqBaggageD);
                String s2 = sampleServiceD.hello();
                sendAppResponse(s1 + s2);
                LOGGER.info("--b4---:" + RpcInvokeContext.getContext());
                // 返回写在这里可能没用
                context.putResponseBaggage("respBaggageB_useless2", "在返A之前写后没用");
                latch.countDown();
            }
        });
        sampleServiceC.hello();
        context.putResponseBaggage("respBaggageB_useful2", "在返A之前写入有用");
        LOGGER.info("--b2---:" + RpcInvokeContext.getContext());
        // 模拟Callback更早回来的行为
        latch.await(5000, TimeUnit.MILLISECONDS);
        // 返回写在这里可能没用
        context.putResponseBaggage("respBaggageB_useless2", "在返A之前写后没用");
        LOGGER.info("--b5---:" + RpcInvokeContext.getContext());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) BoltSendableResponseCallback(com.alipay.sofa.rpc.message.bolt.BoltSendableResponseCallback) CountDownLatch(java.util.concurrent.CountDownLatch) RequestBase(com.alipay.sofa.rpc.core.request.RequestBase)

Aggregations

RequestBase (com.alipay.sofa.rpc.core.request.RequestBase)6 BoltSendableResponseCallback (com.alipay.sofa.rpc.message.bolt.BoltSendableResponseCallback)6 RpcInvokeContext (com.alipay.sofa.rpc.context.RpcInvokeContext)5 CountDownLatch (java.util.concurrent.CountDownLatch)2 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)1 EchoResponse (com.alipay.sofa.rpc.server.bolt.pb.EchoResponse)1