调用触发事件通知
在调用前后出现异常时的事件通知
特性说明
在调用之前、调用之后、出现异常时,会触发 oninvoke、onreturn、onthrow 三个事件,可以配置当事件发生时,通知哪个类的哪个方法。
使用场景
调用服务方法前我们可以记录开始时间,调用结束后统计整个调用耗费,发生异常时我们可以告警或打印错误日志或者调用服务前后记录请求日志、响应日志等。
参考用例 dubbo-samples-notify
使用方式
服务提供者与消费者共享服务接口
1. interface IDemoService {
2. public Person get(int id);
3. }
服务提供者实现
1. class NormalDemoService implements IDemoService {
2. public Person get(int id) {
3. return new Person(id, "charles`son", 4);
4. }
5. }
服务提供者配置
1. <dubbo:application name="rpc-callback-demo" />
2. <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
3. <bean id="demoService" class="org.apache.dubbo.callback.implicit.NormalDemoService" />
4. <dubbo:service interface="org.apache.dubbo.callback.implicit.IDemoService" ref="demoService" version="1.0.0" group="cn"/>
服务消费者 Callback 接口
1. interface Notify {
2. public void onreturn(Person msg, Integer id);
3. public void onthrow(Throwable ex, Integer id);
4. }
服务消费者 Callback 实现
1. class NotifyImpl implements Notify {
2. public Map<Integer, Person> ret = new HashMap<Integer, Person>();
3. public Map<Integer, Throwable> errors = new HashMap<Integer, Throwable>();
5. public void onreturn(Person msg, Integer id) {
6. System.out.println("onreturn:" + msg);
7. ret.put(id, msg);
8. }
10. public void onthrow(Throwable ex, Integer id) {
11. errors.put(id, ex);
12. }
13. }
服务消费者 Callback 配置
两者叠加存在以下几种组合情况:
- 异步回调模式:
async=true onreturn="xxx" - 同步回调模式:
async=false onreturn="xxx" - 异步无回调 :
async=true - 同步无回调 :
async=false
callback 与 async 功能正交分解,async=true 表示结果是否马上返回,async=false 默认,onreturn 表示是否需要回调。
1. <bean id ="demoCallback" class = "org.apache.dubbo.callback.implicit.NotifyImpl" />
2. <dubbo:reference id="demoService" interface="org.apache.dubbo.callback.implicit.IDemoService" version="1.0.0" group="cn" >
3. <dubbo:method name="get" async="true" onreturn = "demoCallback.onreturn" onthrow="demoCallback.onthrow" />
4. </dubbo:reference>
测试代码
1. IDemoService demoService = (IDemoService) context.getBean("demoService");
2. NotifyImpl notify = (NotifyImpl) context.getBean("demoCallback");
3. int requestId = 2;
4. Person ret = demoService.get(requestId);
5. Assert.assertEquals(null, ret);
6. //for Test:只是用来说明callback正常被调用,业务具体实现自行决定.
7. for (int i = 0; i < 10; i++) {
8. if (!notify.ret.containsKey(requestId)) {
9. Thread.sleep(200);
10. } else {
11. break;
12. }
13. }
14. Assert.assertEquals(requestId, notify.ret.get(requestId).getId());
最后修改 September 13, 2024: Refactor website structure (#2860) (1a4b998f54b)
