有没有更好的方式来跟踪订户的变化?
问题描述:
假设我们有一个Client
类,它带有将消息发送到服务器队列的方法。它也订阅了排队和服务器会发送一个通知回到所有客户端时,它从任何注册用户都接收新的消息:有没有更好的方式来跟踪订户的变化?
public class Client {
public void sendMessage(String message) {
// Method to send messages to server
}
public void messageDelivered(String receivedMessage) {
// This is a method subscribed successfull message delivering
}
}
在另一类我想instansiate我的客户端,发送消息和检查一下它successfuly发送:
public class ParentClass {
protected boolean checkConnection() {
Client client = new Client(); // Lets skip all configuration and connection details
String testMessage = "Test message";
client.sendMessage(testMessage);
// Check that messageDelivered() was called in client with testMessage parameter
return result;
}
}
什么是检查messageDelivered()
被称为asynchroniously内部父checkConnection()
方法的最佳方法是什么?
我看到了简单的解决方案,在客户端类中创建一个标志,在消息传递时更新它,并在父类中由时间限制的某个循环中检查此标志。但是这个选项对我来说看起来很脏。也许在Java SDK中有更好的实践或“观察者”?
答
也许这样的事情?
public class Client {
private Runnable runnable;
public void sendMessage(String message, Runnable runnable) {
// Method to send messages to server
this.runnable = runnable;
}
public void messageDelivered(String receivedMessage) {
// This is a method subscribed successfull message delivering
this.runnable.run();
}
}
然后创建一个在您ParentClass
一个Runnable
,并把它传递到客户端。
public class ParentClass {
protected boolean checkConnection() {
Client client = new Client(); // Lets skip all configuration and connection details
String testMessage = "Test message";
// Check that messageDelivered() was called in client with testMessage parameter
MyRunnable runnable = new MyRunnable();
client.sendMessage(testMessage, runnable);
try {
runnable.wait(10000); // Wait for 10 seconds
} catch(InterruptedException e) {
e.printStackTrace();
}
return runnable.getResult();
}
}
运行的类:
public class MyRunnable implements Runnable {
private boolean result;
public MyRunnable() {
this.result = false;
}
@Override
public void run() {
this.result = true;
this.notifyAll();
}
public boolean getResult() {
return this.result;
}
}
如果异步调用,它不能被称为'里面checkConnection()',这两位是你的代码示例中相互排斥。 –
@ M.Prokhorov可以通过以下方式完成: \t retries = 1000; \t DO { \t如果(client.deliveredResult ==真){ \t //成功 \t} \t睡眠(1000); \t retries--; \t} while(retries> 0); 和client.deliveredResult将在执行'messageDelivered()'时设置为true。但我想知道是否有更优雅的解决方案。 (对不起,它搞砸了格式化) – diko
为什么不作为sendMessage的第二个参数添加回调('Runnable'或'Consumer)?一个客户端会触发该参数,当一个成功的响应来自服务器 –
Andrew