编写一个filter
以编写一个监控方法运行时间为例
- 创建一个新的maven模块
- 编写一个类实现Filter接口
MyFilter.java
package com.sherlock.service;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
/**
@Activate group 指在哪个模块失效,下面的意思, 只在消费者端生效
*/
@Activate(group = {CommonConstants.CONSUMER})
public class MyFilter implements Filter {
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
long startTime = System.currentTimeMillis();
try {
return invoker.invoke(invocation); // 执行具体方法
} finally {
long endTime = System.currentTimeMillis();
long l = endTime - startTime;
System.out.println("运行时间 " + l + "ms");
}
}
}
-
在resources目录下, 创建meta-inf\dubbo目录, 然后在创建名为 org.apache.dubbo.rpc.Filter的文件,里面的内容写myFilter=com.sherlock.service.MyFilter (=号后面的值为 包名.过滤器的名字
)
-
上面3步就已经完成了一个简单的fliter的编写, 使用的话, 以上一篇编写的dubbo入门案例为例, 在consumer模块pom文件中引入当前filter这个模块, 运行调用方法,就可以看到控制台打印方法的运行时间了