Reactive REST services

Reactive REST services have been added by using WebFlux as a part of the Spring web stack. This allows us to implement endpoints that are capable of delivering information as streams.

Let's review how this works from a practical viewpoint. Suppose that you want to retrieve notifications that are often pushed by users. Without using the reactive approach, you can retrieve all of the notifications created until the request is made; but, with the reactive approach, you can keep receiving new notifications, which means that if a new notification is created, you will receive it at that exact moment. Let's analyze the following code snippet:

@GetMapping(value = "/{singer}/comments", produces = 
MediaType.TEXT_EVENT_STREAM_VALUE
)
public Flux<Comment> querySingerComments(@PathVariable
String singer)
{
// generate one flux element per second
Flux<Long> intervalToGenerateComments =
Flux.interval(Duration.ofSeconds(1));
Flux<Comment> comments = Flux.fromStream(Stream.generate(()
->new Comment(composeComment(singer), new Date())));
return Flux.zip(intervalToGenerateComments, comments)
.map(fluxTuple -> fluxTuple.getT2());
}

First of all, pay attention to the produced content. This is a stream value, rather than JSON, XML, or any other content type. Next, we are simulating that a new comment is created every second (check the code in bold). At the end of the process, that information is delivered by the endpoint. You can give this a try with the following curl command:

curl http://localhost:8080/jlo/comments

Now, you can see how a new comment is being retrieved each second. This feature opens up a new world of opportunities and functionalities that can be implemented in our applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.253.31