- 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.
- 物聯(lián)網(wǎng)智慧安監(jiān)技術(shù)
- 物聯(lián)網(wǎng)信息安全
- Web Application Development with R Using Shiny
- WordPress 5 Complete
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 互聯(lián)網(wǎng)基礎(chǔ)資源技術(shù)與應(yīng)用發(fā)展態(tài)勢(shì)(2021—2023)
- 物聯(lián)網(wǎng)時(shí)代
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 城市治理一網(wǎng)統(tǒng)管
- 精通SEO:100%網(wǎng)站流量提升密碼
- RestKit for iOS
- Cisco無(wú)線(xiàn)局域網(wǎng)配置基礎(chǔ)
- 互聯(lián)網(wǎng)戰(zhàn)略變革與未來(lái)
- 網(wǎng)絡(luò)基本通信約束下的系統(tǒng)性能極限分析與設(shè)計(jì)
- XSS跨站腳本攻擊剖析與防御