Dubbo探索(五)

事件通知git

在調用以前,調用以後,出現異常時,會觸發oninvoke, onreturn, onthrow三個事件,能夠配置當事件發生時,通知哪一個類的哪一個方法。github

消費方實現Notify接口,以下:api

 1 /**
 2  * Version: 3.0
 3  * Author: pattywgm
 4  * Time: 17/6/29 下午11:01
 5  * Desc: 事件通知接口
 6  */
 7 public interface Notify {
 8     /**
 9      *
10      * @param res 返回值
11      * @param args 入參
12      */
13     public void onreturn(Object res, Object... args);
14 
15     /**
16      *
17      * @param ex 異常對象
18      * @param args 入參
19      */
20     public void onthrow(Throwable ex, Object... args);
21 
22     /**
23      *
24      * @param args 入參
25      */
26     public void oninvoke(Object... args);
27 }
28 
29 
30 @Service("notifyImpl")
31 public class NotifyImpl implements Notify {
32     @Override
33     public void onreturn(Object res, Object... args) {
34         System.out.println("onreturn:" + res.toString());
35 
36     }
37 
38     @Override
39     public void onthrow(Throwable ex, Object... args) {
40 
41         System.out.println("onthrow: " + ex.getMessage());
42     }
43 
44     @Override
45     public void oninvoke(Object... args) {
46         System.out.println("oninvoke: " + args[0]);
47     }

配置UserService的findUserById()方法,添加事件通知,以下:app

1 <dubbo:reference id="userService" group="db" interface="com.patty.dubbo.api.service.UserService"
2                      timeout="10000" retries="3" mock="true" check="false">
3         <dubbo:method name="findAllUsers" merger="myMerger" cache="lru">
4         </dubbo:method>
5         <dubbo:method name="findUserById" async="false" onreturn="notifyImpl.onreturn" onthrow="notifyImpl.onthrow">
6         </dubbo:method>
7 </dubbo:reference>

onreturn指定調用notifyImpl的onreturn方法, onthrow指定調用notifyImpl的onthrow方法。運行中打印結果信息爲:async

onreturn: UserVo info: name-> 李麗, age -> 23, phoneNo -> 17709801256
onthrow: null pointer happend (在UserService的實現中,模擬拋出一個空指針異常)ide

 

代碼參考:https://github.com/pattywgm/dubbo-demo.gitspa

相關文章
相關標籤/搜索