非同步執行

Dubbo 服務提供者的非同步執行

本文件已不再維護。您目前正在檢視快照版本。如果您想查看最新版本的文件,請參閱 最新版本

提供者端的非同步執行將阻塞業務從 Dubbo 的內部執行緒池切換到業務定義的執行緒,避免過度佔用 Dubbo 執行緒池,並有助於避免不同服務之間的相互影響。非同步執行等同於節省資源或提高 RPC 回應效能,因為如果需要阻塞業務執行,則始終需要一個執行緒來負責執行。

定義 CompletableFuture 簽章的介面

服務介面定義

public interface AsyncService {
    CompletableFuture<String> sayHello(String name);
}

服務實作

public class AsyncServiceImpl implements AsyncService {
    @Override
    public CompletableFuture<String> sayHello(String name) {
        RpcContext savedContext = RpcContext. getContext();
        // It is recommended to provide a custom thread pool for supplyAsync and avoid using the JDK public thread pool
        return CompletableFuture. supplyAsync(() -> {
            System.out.println(savedContext.getAttachment("consumer-key1"));
            try {
                Thread. sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "async response from provider.";
        });
    }
}

透過 return CompletableFuture.supplyAsync(),業務執行已從 Dubbo 執行緒切換到業務執行緒,避免阻塞 Dubbo 執行緒池。

使用 AsyncContext

Dubbo 提供了一個類似於 Servlet 3.0 的非同步介面 AsyncContext,它也可以在沒有 CompletableFuture 簽章介面的情況下在提供者端實現非同步執行。

服務介面定義

public interface AsyncService {
    String sayHello(String name);
}

服務暴露與普通服務完全相同

<bean id="asyncService" class="org.apache.dubbo.samples.governance.impl.AsyncServiceImpl"/>
<dubbo:service interface="org.apache.dubbo.samples.governance.api.AsyncService" ref="asyncService"/>

服務實作

public class AsyncServiceImpl implements AsyncService {
    public String sayHello(String name) {
        final AsyncContext asyncContext = RpcContext. startAsync();
        new Thread(() -> {
            // If you want to use the context, it must be executed in the first sentence
            asyncContext.signalContextSwitch();
            try {
                Thread. sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // write back the response
            asyncContext.write("Hello " + name + ", response from provider.");
        }).start();
        return null;
    }
}

上次修改時間:2023 年 1 月 2 日:增強英文文件 (#1798) (95a9f4f6c1c)