Package org.apache.dubbo.rpc
Interface AsyncContext
- All Known Implementing Classes:
AsyncContextImpl
public interface AsyncContext
AsyncContext works like in the Servlet 3.0.
An AsyncContext is stated by a call to
RpcContext.startAsync().
The demo is and
-
Method Details
-
write
write value and complete the async context.- Parameters:
value- invoke result
-
isAsyncStarted
boolean isAsyncStarted()- Returns:
- true if the async context is started
-
stop
boolean stop()change the context state to stop -
start
void start()change the context state to start -
signalContextSwitch
void signalContextSwitch()Signal RpcContext switch. Use this method to switch RpcContext from a Dubbo thread to a new thread created by the user. Note that you should use it in a new thread like this:public class AsyncServiceImpl implements AsyncService { public String sayHello(String name) { final AsyncContext asyncContext = RpcContext.startAsync(); new Thread(() -> { // right place to use this method asyncContext.signalContextSwitch(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } asyncContext.write("Hello " + name + ", response from provider."); }).start(); return null; } } -
resetContext
void resetContext()Reset Context is not necessary. Only reset context after result was write back if it is necessary.public class AsyncServiceImpl implements AsyncService { public String sayHello(String name) { final AsyncContext asyncContext = RpcContext.startAsync(); new Thread(() -> {// the right place to use this method asyncContext.signalContextSwitch();
try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } asyncContext.write("Hello " + name + ", response from provider."); // only reset after asyncContext.write() asyncContext.resetContext(); }).start(); return null; } }
public class AsyncServiceImpl implements AsyncService { public CompletableFuture sayHello(String name) { CompletableFuture future = new CompletableFuture(); final AsyncContext asyncContext = RpcContext.startAsync(); new Thread(() -> { // the right place to use this method asyncContext.signalContextSwitch(); // some operations... future.complete(); // only reset after future.complete() asyncContext.resetContext(); }).start(); return future; } }
-