2015-11-22 57 views
0

這是我可以詳細闡述的在REST調用中獲得與Reactor的異步性的最佳想法,可用性如下:我不滿意..有關如何更好地實現它的任何想法?帶DeferredResult和Reactor的Spring異步REST

complete code here for reference

REST接口:

@RestController 
public class REST_Interface { 

    @Autowired 
    public EventBus eventBus; 

    @RequestMapping("/getGreeting/{name}") 
    public DeferredResult<String> getGreeting(@PathVariable String name) { 

     DeferredResult<String> result = new DeferredResult<>(); 

     EventWrapper<String> wrapper = new EventWrapper<>(result, name); 
     eventBus.notify("greeting.topic", Event.wrap(wrapper)); 

     return result; 
     } 
} 

EventWrapper:

public class EventWrapper<T> { 
    private DeferredResult<T> deferredResult; 
    private T payload; 

    public EventWrapper(DeferredResult<T> deferredResult, T payload) { 
     this.deferredResult = deferredResult; 
     this.payload = payload; 
    } 
    // Getters & Setters 
} 

事件消費者:

@Consumer 
public class EventConsumer { 

    @Autowired 
    public EventBus eventBus; 

    @Selector("greeting.topic") 
    public void onTestTopic(Object o) { 
     System.out.println("Event receved for Logging " + o.toString()); 
    } 

    @Selector("greeting.topic") 
    public void wrappedGreeter(EventWrapper<String> ew) { 

     ew.getDeferredResult().setResult("Ciao " + ow.getPayload().toUpperCase()); 
    } 
} 

回答

2

看看EventBus.sendAndReceive(),它正是爲這種用例而準備的。來自http://projectreactor.io/docs/reference/#bus-request-reply的示例:

EventBus bus; 

bus.receive($("job.sink"), (Event<String> ev) -> { 
    return ev.getData().toUpperCase(); 
}); 

bus.sendAndReceive(
    "job.sink", 
    Event.wrap("Hello World!"), 
    s -> System.out.printf("Got %s on thread %s%n", s, Thread.currentThread()) 
); 
+1

在Java中,它看起來不太好看。 :D 無論如何,這種方式迫使所有事件鏈下坡使用相同的方法,所以不再是事件驅動的範例,而只是一個異步系列的調用。 –