服务器回调客户端
通过参数回调从服务器端调用客户端逻辑
功能描述
参数回调方法与调用本地回调或监听器相同,您只需要在 Spring 配置文件中声明哪个参数是回调类型。Dubbo 将基于持久连接生成一个反向代理,以便可以从服务器端调用客户端逻辑。您可以参考 dubbo 项目中的示例代码.
使用场景
回调函数通知客户端执行结果,或发送通知。当方法执行时间较长时,类似于异步调用,在审批流程中回调客户端审批结果。
如何使用
服务接口示例
CallbackService.java
package com. callback;
public interface CallbackService {
void addListener(String key, CallbackListener listener);
}
CallbackListener.java
package com. callback;
public interface CallbackListener {
void changed(String msg);
}
服务提供者接口实现示例
package com.callback.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.callback.CallbackListener;
import com.callback.CallbackService;
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); // Timely trigger change notification
} catch (Throwable t) { // defensive fault tolerance
t. printStackTrace();
}
}
}
});
t. setDaemon(true);
t. start();
}
public void addListener(String key, CallbackListener listener) {
listeners. put(key, listener);
listener.changed(getChanged(key)); // send change notification
}
private String getChanged(String key) {
return "Changed: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
服务提供者配置示例
<bean id="callbackService" class="com.callback.impl.CallbackServiceImpl" />
<dubbo:service interface="com.callback.CallbackService" ref="callbackService" connections="1" callbacks="1000">
<dubbo:method name="addListener">
<dubbo:argument index="1" callback="true" />
<!--You can also specify the type -->
<!--<dubbo:argument type="com.demo.CallbackListener" callback="true" />-->
</dubbo:method>
</dubbo:service>
服务消费者配置示例
<dubbo:reference id="callbackService" interface="com.callback.CallbackService" />
服务消费者调用示例
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
context. start();
CallbackService callbackService = (CallbackService) context. getBean("callbackService");
callbackService.addListener("foo.bar", new CallbackListener(){
public void changed(String msg) {
System.out.println("callback1:" + msg);
}
});
上次修改时间:2023 年 1 月 2 日:增强 en 文档 (#1798) (95a9f4f6c1c)