參數回調 callbacks
阿新 • • 發佈:2018-06-15
代理 ssm ring row name cat dex ati ont
效果:Consumer調用Provider方法,在Provider方法中回調Consumer提供的方法。
參數回調方式與調用本地 callback 或 listener 相同,只需要在 Spring 的配置文件中聲明哪個參數是 callback 類型即可。Dubbo 將基於長連接生成反向代理,這樣就可以從服務器端調用客戶端邏輯。
服務接口示例
CallbackService.java
public interface CallbackService { void addListener(String key, CallbackListener listener); }
CallbackListener.java
public interface CallbackListener { void changed(String msg); }
服務提供者接口實現示例
public class CallbackServiceImpl implements CallbackService{ private final Map<String, CallbackListener> listeners = new ConcurrentHashMap<String, CallbackListener>(); public CallbackServiceImpl() { Thread t= new Thread(new Runnable() { public void run() { while(true) { try { for(Map.Entry<String, CallbackListener> entry : listeners.entrySet()){ try { entry.getValue().changed(getChanged(entry.getKey())); }catch (Throwable t) { listeners.remove(entry.getKey()); } } Thread.sleep(5000); // 定時觸發變更通知 } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.setDaemon(true); t.start(); } public void addListener(String key, CallbackListener listener) { listeners.put(key, listener); listener.changed(getChanged(key)); // 發送變更通知 } private String getChanged(String key) { return "Changed: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } }
服務提供者配置示例
<bean id="callbackService" class="com.ssmp.serviceImpl.CallbackServiceImpl" /> <dubbo:service interface="com.ssmp.service.CallbackService" ref="callbackService" connections="1" callbacks="1000"> <dubbo:method name="addListener"> <dubbo:argument index="1" callback="true" /> <!--也可以通過指定類型的方式--> <!--<dubbo:argument type="com.demo.CallbackListener" callback="true" />--> </dubbo:method> </dubbo:service>
服務消費者配置示例
<dubbo:reference id="callbackService" interface="com.ssmp.service.CallbackService" />
服務消費者調用示例
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/user-consumer.xml"); context.start(); CallbackService callbackService = (CallbackService) context.getBean("callbackService"); callbackService.addListener("http://10.20.160.198/wiki/display/dubbo/foo.bar", new CallbackListener(){ public void changed(String msg) { System.out.println("callback1:" + msg); } }); System.in.read();
參數回調 callbacks