一、实现Filter接口
1、消费者过滤器:ConsumerTraceFilter.java
packagecom.dubbo.demo.Filter;import com.alibaba.dubbo.rpc.*;importjava.util.Map;importjava.util.UUID;public class ConsumerTraceFilter implementsFilter {
@Overridepublic Result invoke(Invoker> invoker, Invocation invocation) throwsRpcException {
Map stringStringMap =invocation.getAttachments();//设置参数
stringStringMap.put("patentId","0");
stringStringMap.put("traceId",UUID.randomUUID().toString());
System.out.println("生成tradeId:"+stringStringMap.get("traceId"));returninvoker.invoke(invocation);
}
}
2、生产者过滤器:ProviderTraceFilter.java
packagecom.dubbo.demo.Filter;import com.alibaba.dubbo.rpc.*;importjava.util.Map;public class ProviderTraceFilter implementsFilter {public Result invoke(Invoker> invoker, Invocation invocation) throwsRpcException {
Map stringStringMap =invocation.getAttachments();//接收参数
System.out.println("收到:patentId:"+stringStringMap.get("patentId"));
System.out.println("收到:tradeId:"+stringStringMap.get("traceId"));returninvoker.invoke(invocation);
}
}
二、配置SPI Filter扩展文件
1、生产者配置
在目录:resources/META-INF/dubbo/ 创建com.alibaba.dubbo.rpc.Filter(纯文本文件.txt)
内容:
traceFilter=com.dubbo.demo.Filter.ProviderTraceFilter
2、消费者配置
在目录:resources/META-INF/dubbo/ 创建com.alibaba.dubbo.rpc.Filter(纯文本文件.txt)
内容:
traceFilter=com.dubbo.demo.Filter.ConsumerTraceFilter
三、配置dubbo文件
1、生产者
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
2、消费者
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
四、验证
依次启动生产者、消费者发起远程调用
示例代码:
https://github.com/Star-Lordxing/dubbo-demo
原文:https://www.cnblogs.com/wangzhuxing/p/9738906.html