Hands-On Reactive Programming in Spring 5
上QQ阅读APP看书,第一时间看更新

Criticism of the solution

At this point, we may praise ourselves for implementing a resilient reactive application using only a few dozen code lines (including HTML and JavaScript). However, the current solution has a few issues. First of all, we are using the Publish-Subscribe infrastructure provided by Spring. In Spring Framework, this mechanism was initially introduced for handling application life cycle events, and was not intended for high-load, high-performance scenarios. What would happen when, instead of one stream of temperature data, we need thousands or even millions of separate streams? Will Spring's implementation be able to handle such a load efficiently?

Furthermore, one significant downside of such an approach lies in the fact that we are using an internal Spring mechanism to define and implement our business logic. This leads to a situation in which some minor changes in the framework may break our application. Besides, it is hard to unit test our business rules without running the application context. As explained in Chapter 1, Why Reactive Spring?, it is also reasonable to mention an application that has a lot of methods that are decorated with the @EventListener annotation, and without an explicit script that describes the whole workflow in one concise piece of code.

Furthermore, SseEmitter has a notion for errors and the ends of streams, whereas @EventListener does not. So, to signal the end of the stream or error between components, we have to define some special objects or class hierarchies, and it is easy to forget about handling them. Also, such specific markers may have slightly different semantics in different situations, complicating the solution and reducing the attractiveness of the approach.

One more drawback worth highlighting is that we allocate the thread pool to asynchronously broadcast temperature events. In the case of a genuinely asynchronous and reactive approach (framework), we wouldn't have to do this.

Our temperature sensor generates only one stream of events without regard to how many clients are listening. However, it also creates them when nobody listens. That may lead to a waste of resources, especially when creation actions are resource hungry. For example, our component may communicate with real hardware and reduce hardware lifespan at the same time.

To address all of these issues, as well as others, we need a reactive library that is specially designed for such purposes. Fortunately, we have a few of these. We will now look at RxJava, which was the first widely adopted reactive library, and changed the way we build reactive applications using Java.