事件通知
在調用之前、調用之后、出現異常時,會觸發 oninvoke、onreturn、onthrow 三個事件,可以配置當事件發生時,通知哪個類的哪個方法 1。
服務提供者與消費者共享服務接口
interface IDemoService { public Person get(int id); }
服務提供者實現
class NormalDemoService implements IDemoService { public Person get(int id) { return new Person(id, "charles`son", 4); } }
服務提供者配置
<dubbo:application name="rpc-callback-demo" /> <dubbo:registry address="http://10.20.160.198/wiki/display/dubbo/10.20.153.186" /> <bean id="demoService" class="com.alibaba.dubbo.callback.implicit.NormalDemoService" /> <dubbo:service interface="com.alibaba.dubbo.callback.implicit.IDemoService" ref="demoService" version="1.0.0" group="cn"/>
服務消費者 Callback 接口
interface Notify { public void onreturn(Person msg, Integer id); public void onthrow(Throwable ex, Integer id); }
服務消費者 Callback 實現
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); } }
服務消費者 Callback 配置
<bean id ="demoCallback" class = "com.alibaba.dubbo.callback.implicit.NofifyImpl" /> <dubbo:reference id="demoService" interface="com.alibaba.dubbo.callback.implicit.IDemoService" version="1.0.0" group="cn" > <dubbo:method name="get" async="true" onreturn = "demoCallback.onreturn" onthrow="demoCallback.onthrow" /> </dubbo:reference>
callback 與 async 功能正交分解,async=true 表示結果是否馬上返回,onreturn 表示是否需要回調。
兩者疊加存在以下幾種組合情況 2:
- 異步回調模式:
async=true onreturn="xxx" - 同步回調模式:
async=false onreturn="xxx" - 異步無回調 :
async=true - 同步無回調 :
async=false
測試代碼
IDemoService demoService = (IDemoService) context.getBean("demoService"); NofifyImpl notify = (NofifyImpl) context.getBean("demoCallback"); int requestId = 2; Person ret = demoService.get(requestId); Assert.assertEquals(null, ret); //for Test:只是用來說明callback正常被調用,業務具體實現自行決定. for (int i = 0; i < 10; i++) { if (!notify.ret.containsKey(requestId)) { Thread.sleep(200); } else { break; } } Assert.assertEquals(requestId, notify.ret.get(requestId).getId());
