dubbo 事件通知
官网:https://dubbo.apache.org/zh/docs/advanced/events-notify/
事件通知
应用:消费端调用服务端服务之前、正常返回、出现异常时,可触发对应的事件通知(oninvoke、onreturn、onthrow)
服务端:服务接口
interface IDemoService {
public Person get(int id);
}
服务端:服务接口实现
@DubboService
public class NormalDemoService implements IDemoService {
public Person get(int id) {
return new Person(id, "charles`son", 4);
}
}
消费端:事件通知接口
interface Notify {
public void onreturn(Person msg, Integer id);
public void onthrow(Throwable ex, Integer id);
}
消费端:事件通知接口实现
public class NotifyImpl implements Notify {
public Map<Integer, Person> ret = new HashMap<Integer, Person>();
public Map<Integer, Throwable> errors = new HashMap<Integer, Throwable>();
public void onreturn(Person msg, Integer id) {
System.out.println("onreturn:" + msg);
ret.put(id, msg);
}
public void onthrow(Throwable ex, Integer id) {
errors.put(id, ex);
}
}
消费端:事件通知配置
<bean id ="demoCallback" class = "org.apache.dubbo.callback.implicit.NotifyImpl" />
<dubbo:reference id="demoService" interface="org.apache.dubbo.callback.implicit.IDemoService" version="1.0.0" group="cn" >
<dubbo:method name="get" async="true" onreturn = "demoCallback.onreturn" onthrow="demoCallback.onthrow" />
</dubbo:reference>
# async:默认false,即事件通知同步执行
async=true onreturn="xxx":异步通知
async=false onreturn="xxx":同步通知
async=true:异步无回调
async=false:同步无回调
实现原理
FutureFilter:消费端事件通知过滤器
@Activate(group = CommonConstants.CONSUMER) //消费端过滤器
public class FutureFilter implements ClusterFilter, ClusterFilter.Listener {