使用 Apache Ignite 的消息模块可以很容易地在节点间发送消息并获得同步响应。下面是一个示例代码:
Ignite ignite = Ignition.start();
IgniteMessaging messaging = ignite.message();
// 发送异步消息并注册回调
messaging.send("topic", "message", new IgniteBiPredicate() {
@Override
public boolean apply(UUID nodeId, String msg) {
System.out.println("Received message: " + msg + " from node " + nodeId);
return true; // 返回 true 表示已处理消息
}
});
// 发送同步消息并等待响应
Object response = messaging.sendOrdered("topic", "message", 5000);
System.out.println("Received response: " + response);
在这个示例中,首先使用 Ignition.start() 启动了一个 Ignite 节点,并获取了 IgniteMessaging 实例。然后通过 messaging.send() 方法发送了一个异步消息,并注册了一个回调函数,在消息被接收到时会被调用。最后通过 messaging.sendOrdered() 方法发送了一个同步消息,并等待最多 5000 毫秒的响应。当收到响应后,就可以对其进行处理了。
需要注意的是,在 messaging.sendOrdered() 方法中,第二个参数是要发送的消息内容,第三个参数是等待响应的超时时间(以毫秒为单位)。如果在超时时间内未收到响应,方法会抛出 TimeoutException。同时,如果消息发送成功但未收到回调时,send() 方法会返回 true,否则会返回 false。