自定义过滤器组件

参考示例 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
}

过滤器可以加载在消费者端或提供者端。当加载在消费者端时,其 Invoke 函数调用的下游是网络层,在请求完成并从网络层获取返回结果后调用 OnResponse。当加载在提供者端时,其 Invoke 函数调用的下游是用户代码,在用户代码执行并传递到网络层后调用 OnResponse。

过滤器采用面向切面设计的思想。通过合理扩展过滤器,可以记录日志、设置数据管理、记录调用方对应服务器的性能、限制流量等。

2. 框架预定义过滤器

框架预定义了一系列过滤器,可以在配置中直接使用,其代码实现位于 filter

  • accesslog
  • active
  • sign: AuthConsumerFilter
  • auth: AuthProviderFilter -echo
  • execute: ExecuteLimitFilter
  • generic: GenericFilter
  • generic_service: GenericServiceFilter
  • pshutdown: GracefulShutdownProviderFilter -cshutdown: GracefulShutdownConsumerFilter
  • hystrix_consumer: HystrixConsumerFilter
  • hystrix_provider: HystrixProviderFilter
  • metrics
  • seata
  • sentinel-provider
  • sentinel-consumer -token -tps
  • tracing

3. 默认加载过滤器

当用户在配置文件中配置要使用的过滤器时,框架会使用用户配置的过滤器,否则会加载默认过滤器

-消费者

cshutdown

  • 提供者

    echo, metrics, token, accesslog, tps, generic_service, executivete, pshutdown

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)