Creating a reactive controller – StockPriceEventController

Creating a Spring Reactive controller is very similar to creating a Spring MVC controller. The basic constructs are the same: @RestController and the different @RequestMapping annotations. The following snippet shows a simple reactive controller named StockPriceEventController:

    @RestController
public class StockPriceEventController {

@GetMapping("/stocks/price/{stockCode}")
Flux < String > retrieveStockPriceHardcoded
(@PathVariable("stockCode") String stockCode) {
return Flux.interval(Duration.ofSeconds(5))
.map(l -> getCurrentDate() + " : "
+ getRandomNumber(100, 125))
.log();
}

private String getCurrentDate() {
return (new Date()).toString();
}

private int getRandomNumber(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}

}

A few important things to note are as follows:

  • @RestController and @GetMapping("/stocks/price/{stockCode}"): Basic constructs are the same as Spring MVC. We are creating a mapping to the specified URI.
  • Flux<String> retrieveStockPriceHardcoded(@PathVariable("stockCode") String stockCode): Flux represents a stream of 0 to n elements. The return type, Flux<String>, indicates that this method returns a stream of values representing the current price of a stock.
  • Flux.interval().map(l -> getCurrentDate() + " : " + getRandomNumber(100, 125)): We are creating a hard-coded Flux returning a stream of random numbers.
  • Duration.ofSeconds(5): Stream elements are returned every 5 seconds.
  • Flux.<<****>>.log(): Invoking the log() method on Flux helps observe all Reactive streams signals and trace them using logger support.
  • private String getCurrentDate(): Returns the current time as a string.
  • private int getRandomNumber(int min, int max): Returns a random number between min and max.
..................Content has been hidden....................

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