本地存根

理解 Dubbo3 中使用本地樁(Stub)在客戶端執行部分邏輯

功能描述

遠端服務後,客戶端通常只有介面,實作都在伺服器端,但提供者有時希望在客戶端執行一些邏輯。

/user-guide/images/stub.jpg

使用場景

做 ThreadLocal 快取、提前驗證參數、呼叫失敗後偽造容錯資料等。此時需要在 API 中帶一個 Stub,客戶端生成一個 Proxy 實例,會透過建構函式將 Proxy 傳遞給 Stub1,然後將 Stub 暴露給使用者,Stub 可以決定是否呼叫 Proxy。

使用方法

Spring 配置檔案設定

<dubbo:consumer interface="com.foo.BarService" stub="true" />

<dubbo:consumer interface="com.foo.BarService" stub="com.foo.BarServiceStub" />

提供 Stub 實作2

package com.foo;
public class BarServiceStub implements BarService {
    private final BarService barService;
    
    // The constructor passes in the real remote proxy object
    public BarServiceStub(BarService barService){
        this. barService = barService;
    }
 
    public String sayHello(String name) {
        // This code is executed on the client side, you can do ThreadLocal local cache on the client side, or pre-verify whether the parameters are legal, etc.
        try {
            return barService.sayHello(name);
        } catch (Exception e) {
            // You are fault tolerant and can do any AOP interception
            return "fault tolerance data";
        }
    }
}

  1. Stub 必須有一個可以傳入 Proxy 的建構函式。 ↩︎

  2. 在介面旁邊放置一個 Stub 實作,它實作 BarService 介面,並且有一個傳入遠端 BarService 實例的建構函式。 ↩︎


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