Guava EventBus:如何从事件处理程序返回结果

sto*_*esh 3 java events event-handling guava

我有一个Web服务,它从另一个系统接收xml事件,使用特定的工作流程处理它们,并将一个潜在错误列表作为HTTP响应发回.

事件处理工作流由几个处理程序组成(比方说:Preprocessor,PersisterValidator),使用Guava的EventBus实现.处理程序相互发送事件.像这样的东西:

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 
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是:如何将处理结果Validator处理程序深深地返回到起始点(RequestHandler),以便用户可以接收HTTP响应?

我考虑两个选择:

  1. 将errors对象设置为初始XmlReceivedEvent并在处理完成后检索它:

    public class RequestHandler {
    
        @RequestMapping
        public Errors handleRequest(String xmlData) {
            XmlReceivedEvent event = new XmlReceivedEvent(xmlData);
            eventBus.post(event);
            ...
            return event.getErrors(); 
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,我将不得不将错误对象传递给链中的每个事件,以使Validator可以使用实际数据填充它.

  1. Validator订阅RequestHandlerValidationCompleteEvent,里面有填充的错误对象.

    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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

但是,遗憾的是,RequestHandler是一个Spring无状态服务(singleton),所以我想避免在类字段中保存任何数据.

欣赏任何想法.

Col*_*inD 10

如果你想要这样的工作流程,你不应该使用番石榴EventBus.EventBus特别旨在允许事件发布给订阅者,而事件海报不知道或关心这些订阅者是什么......因此,您无法将结果返回给订阅者的活动海报.

听起来像你应该在这里做一些更简单的事情,比如注入你的预处理器,persister和验证器并直接调用它们的方法.