自訂過濾器組件

參考範例 dubbo-go-samples/filter

1. 過濾器概念

// Filter interface defines the functions of a filter
// Extension - Filter
type Filter interface {
// Invoke is the core function of a filter, it determines the process of the filter
Invoke(context.Context, protocol.Invoker, protocol.Invocation) protocol.Result
// OnResponse updates the results from Invoke and then returns the modified results.
OnResponse(context.Context, protocol.Result, protocol.Invoker, protocol.Invocation) protocol.Result
}

過濾器可以加載在 Consumer 端或 Provider 端。當加載在 Consumer 端時,其 Invoke 函數調用的下游是網路層,在請求完成並從網路層獲得返回結果後調用 OnResponse。當加載在 Provider 端時,其 Invoke 函數調用的下游是使用者代碼,在使用者代碼執行並傳遞到網路層後調用 OnResponse。

過濾器採用面向切面設計的思想。通過合理擴展過濾器,可以記錄日誌、設置數據管理、記錄 invoker 對應伺服器的性能、限制流量等等。

2. 框架預定義過濾器

框架預定義了一系列過濾器,可以直接在配置中使用,其代碼實現位於 filter

  • 訪問日誌
  • 活動
  • 簽名:AuthConsumerFilter
  • 驗證:AuthProviderFilter - 回顯
  • 執行:ExecuteLimitFilter
  • 通用:GenericFilter
  • 通用服務:GenericServiceFilter
  • pshutdown:GracefulShutdownProviderFilter -cshutdown:GracefulShutdownConsumerFilter
  • hystrix_consumer:HystrixConsumerFilter
  • hystrix_provider:HystrixProviderFilter
  • 指標
  • seata
  • sentinel-provider
  • sentinel-consumer -token -tps
  • 追蹤

3. 默認加載過濾器

當用戶在配置文件中配置了要使用的過濾器時,框架會使用用戶配置的過濾器,否則會加載默認過濾器

-Consumer

cshutdown

  • Provider

    迴聲, 指標, 權杖, 存取日誌, 每秒事務處理量, 通用服務, 執行, 關閉

4. 使用者指定的篩選器

指定篩選器時,可以使用「,」分隔

  • 消費者端

    dubbo:
      consumer:
        filter: echo,token,tps,myCustomFilter # Custom filter can be specified
    
  • 提供者端

    dubbo:
      provider:
        services:
          GreeterProvider:
            filter: myCustomFilter, echo, tps
    

5. 自訂篩選器

使用者可以在程式碼中自訂篩選器,將其註冊到框架上,並選擇在配置中使用它。

func init() {
extension. SetFilter("myCustomFilter", NewMyClientFilter)
}

func NewMyClientFilter() filter. Filter {
return &MyClientFilter{}
}

type MyClientFilter struct {
}

func (f *MyClientFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
fmt.Println("MyClientFilter Invoke is called, method Name = ", invocation.MethodName())
return invoker. Invoke(ctx, invocation)
}
func (f *MyClientFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, protocol protocol.Invocation) protocol.Result {
fmt.Println("MyClientFilter OnResponse is called")
return result
}

上次修改時間:2024 年 1 月 17 日:修復損壞的連結 (6651e217e73)