我有一个网络服务,它从另一个系统接收 xml 事件,使用特定的工作流程处理它们,并将潜在错误列表作为 HTTP 响应发回。
事件处理工作流由几个使用 Guava's EventBus 实现的处理程序(比方说:Preprocessor、Persister 和Validator)组成.处理程序相互发送事件。像这样:
public class RequestHandler {
@RequestMapping
public Errors handleRequest(String xmlData) {
eventBus.post(new XmlReceivedEvent(xmlData));
...
return errors; // how to get errors object from the last handler in chain ?
}
}
public class Preprocessor {
@Subscribe
public void onXmlReceived(XmlReceivedEvent event) {
// do some pre-processing
...
eventBus.post(new PreprocessingCompleteEvent(preprocessingResult));
}
}
public class Persister {
@Subscribe
public void onPreprocessingComplete(PreprocessingCompleteEvent event) {
// do some persistence stuff
...
eventBus.post(new PersistenceCompleteEvent(persistenceResult));
}
}
public class Validator {
@Subscribe
public void onPersistenceComplete(PersistenceCompleteEvent event) {
// do validation
...
eventBus.post(new ValidationCompleteEvent(errors)); // errors object created, should be returned back to the RequestHandler
}
}
问题是:如何返回处理结果从Validator处理程序深入返回到起点(RequestHandler),这样用户就可以接收 HTTP 响应?
我考虑了两种选择:
将错误对象设置为初始 XmlReceivedEvent 并在处理完成后检索它:
public class RequestHandler { @RequestMapping public Errors handleRequest(String xmlData) { XmlReceivedEvent event = new XmlReceivedEvent(xmlData); eventBus.post(event); ... return event.getErrors(); } }
但是,在那种情况下,我必须将错误对象传递给链中的每个事件,以使其可供 validator 使用真实数据填充它。
从 Validator 订阅 RequestHandler 到 ValidationCompleteEvent,并在其中填充错误对象。
public class RequestHandler { private Errors errors; @RequestMapping public Errors handleRequest(String xmlData) { XmlReceivedEvent event = new XmlReceivedEvent(xmlData); eventBus.post(event); ... return this.errors; // ??? } @Subscribe public void onValidationComplete(ValidationCompleteEvent event) { this.errors = event.getErrors(); } }
但是,不幸的是,RequestHandler 是一个 Spring 无状态服务(单例),所以我想避免在类字段中保存任何数据。
感谢任何想法。
最佳答案
如果您想要这样的工作流,您不应该为此使用 Guava EventBus
。 EventBus
专门用于允许在事件发布者不知道或关心这些订阅者是什么的情况下将事件发布给订阅者......因此,您无法将结果返回给事件的发布者订阅者。
在我看来你应该在这里做一些更直接的事情,比如注入(inject)你的预处理器、持久化器和 validator 并直接调用它们的方法。
关于java - Guava 事件总线 : How to return result from event handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309778/