- Hands-On Reactive Programming in Spring 5
- Oleh Dokuka Igor Lozynskyi
- 257字
- 2021-07-23 16:36:24
Exposing the SSE endpoint
To expose the SSE endpoint, we need a REST controller that is autowired with the TemperatureSensor instance. The following code shows the controller, which utilizes RxSeeEmitter:
@RestController
public class TemperatureController {
private final TemperatureSensor temperatureSensor; // (1)
public TemperatureController(TemperatureSensor temperatureSensor) {
this.temperatureSensor = temperatureSensor;
}
@RequestMapping(
value = "/temperature-stream",
method = RequestMethod.GET)
public SseEmitter events(HttpServletRequest request) {
RxSeeEmitter emitter = new RxSeeEmitter(); // (2)
temperatureSensor.temperatureStream() // (3)
.subscribe(emitter.getSubscriber()); // (4)
return emitter; // (5)
}
}
The TemperatureController is the same Spring Web MVC @RestController as before. It holds a reference to the TemperatureSensor bean (1). When a new SSE session is created, the controller instantiates our augmented RxSeeEmitter (2) and subscribes to the RxSeeEmitter subscribers (4) to the temperature stream referenced from the TemperatureSensor instance (3). Then the RxSeeEmitter instance is returned to the Servlet container for processing (5).
As we can see with RxJava, the REST controller holds less logic, does not manage the dead SseEmitter instances, and does not care about synchronization. In turn, the reactive implementation manages the routine of the TemperatureSensor's values, reading, and publishing. The RxSeeEmitter translates reactive streams to outgoing SSE messages, and TemperatureController only binds a new SSE session to a new RxSeeEmitter that is subscribed to a stream of temperature readings. Furthermore, this implementation does not use Spring's EventBus, so it is more portable and can be tested without initializing a Spring context.
- 物聯網安全:理論、實踐與創新
- Building RESTful Web Services with Spring 5(Second Edition)
- 網絡的琴弦:玩轉IP看監控
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- WordPress Web Application Development
- IPv6網絡切片:使能千行百業新體驗
- Kong網關:入門、實戰與進階
- 5G技術核心與增強:從R15到R17
- Selenium WebDriver 3 Practical Guide
- bash網絡安全運維
- Qt5 Python GUI Programming Cookbook
- 精通SEO:100%網站流量提升密碼
- 物聯網與智慧農業
- Python API Development Fundamentals
- 人際網絡