Reactive Spring Boot: Part 1: Kotlin REST Service

Reactive Spring Boot: Part 1: Kotlin REST Service


This tutorial is a series of videos outlining
a number of steps to build a full Spring Boot application featuring a Kotlin service back
end, a Java client and a JavaFX user interface. This first step in the tutorial is to create a Kotlin Spring Boot Application which serves
as the back end of the application. In this video we’ll create a REST service
that can be connected to in later parts of the tutorial. Let’s create a new project for our Spring Boot service. Since we’re using Spring Boot we’ll select
the Spring Initializr option on the left of the New Project window. We can select which SDK to use, we’ll use
Java 13 for this project. We enter the group name for our project, and
an artifact name. We can build this project with Maven or Gradle,
and there are various options here. We’re going to create a Maven project which
will generate the pom.xml and maven wrapper files that we need. For this service we’re going to choose Kotlin
as our language. We’ll select Java 11 here as this is the most
recent Long Term Support version for Java, but for the purposes of this project it makes
no difference. The name is automatically populated from the
artifact name, and we don’t need to change this. We should add a useful description for the
project, and we can optionally change the top level package too. We can choose which version of Spring Boot to use, including the most recent production-ready
version, or snapshot versions to try out. We’re going to use 2.2.0 RC1 for this tutorial
because later we’ll be using features that are only available in the release candidate. We can also search for and select which Spring Boot starters we want to use. This is a reactive REST service, so we want
Reactive Web. We’ll use the defaults for project name and
location. IntelliJ IDEA will use Spring Initializr to create the project and then import it correctly
into the IDE. Let’s enable auto-import on Maven so if we
make any changes to the pom.xml file the project will automatically be refreshed and rebuilt. You can see that IntelliJ IDEA automatically
recognises this as a Maven project and opens the Maven window. We don’t need this right now. We also don’t need the build results so let’s
close this too. In the project window we see the structure of the project that has been created, including
a Kotlin directory and the standard default Application class that Spring Boot creates. IntelliJ IDEA Ultimate has full support for Spring applications, which includes gutter
icons making it easier to identify and navigate between Spring elements like Spring Beans. If we take a quick look at the generated pom.xml file, we see not only the selected Spring
Boot starters and Kotlin dependencies, we can also see the Spring compiler plugin in
the Kotlin maven plugin. This makes it a bit simpler to work with Spring
in Kotlin. Let’s run this basic application using the shortcut Ctrl+Shift+F10 for Windows or Linux,
or Ctrl+Shift+R for Mac, just to see everything works together correctly. We can see it’s started successfully, with
Netty running on port 8080. Let’s stop it with Ctrl+F2, r Cmd+F2 for Mac. Now we know it all works, we can get started on our own functionality. Let’s create a class for our REST Controller. We’ll put it in the same Kotlin file to keep
things simple for now. We need to annotated this as a @RestController. We can use the fun1 Live Template to automatically
create a Kotlin function that takes a single parameter. We’ll call this method “prices”, and it takes
the symbol of the stock we want to get the prices for. This method will return a Flux, which will
be a constant stream of prices. This is where the Reactive part comes in. The Flux will emit StockPrices. I use Alt+Enter to get IntelliJ IDEA to automatically
fix up my code, here we import the reactor.Flux, and then we need to create this new StockPrice
class which will represent all the data we need to know about the price of a Stock. Again, we’ll keep this inside the same file
to make it easier to see. We’re going to create this as a Kotlin data class. This is a compact way to declare a class with
properties. In Java, this would have getters, and maybe
setters, and equals, hashCode and toString methods, but in Kotlin we simply declare what
we want in the Constructor parameters. We want a symbol for the stock, which is a
String, a price, which is a Double, and the time associated with that price. Here we’re using Java 8’s java.time.LocalDateTime. Now we’re going to define what the prices method returns. This method is going to create a Flux which
emits one randomly generated price every second. We can do this with an interval with a Duration
of one second. Then we can map to a new StockPrice for each
of these seconds. Note that in Kotlin we don’t need the “new”
keyword. The StockPrice needs the symbol, a price,
which for the purposes of this tutorial will be randomly generated, and a time, which will
be “now”. Let’s import this now() method to make the
code a bit shorter. Let’s create this randomStockPrice function. IntelliJ IDEA knows this needs to return a
Double because of StockPrice constructor. One way to create an arbitrary Double is using
ThreadLocalRandom and the nextDouble method. Let’s generate a number between zero and one
hundred. The last thing we need to do to make sure this compiles is to return this Flux. Since we want to be able to access this method via an HTTP Get call, we need to add the @GetMapping
annotation to it. We’ll give it a path, I tend to define this
as a String param and then get IntelliJ IDEA to turn it into an array call. We need to define what the response to this
method looks like, we’re going to use TEXT_EVENT_STREAM_VALUE so this is a server-sent events streaming
endpoint. Again, I’ll use IntelliJ IDEA to wrap this
in an array. One final warning from IntelliJ IDEA that needs fixing up – the IDE has detected that
we’re using a path variable but haven’t defined it in the method parameters. One way to fix this is to get IntelliJ IDEA
to create the PathVariable, and remove the parameter we created earlier. We run the application, and we can see it start up correctly. If we open up a web browser and navigate to
the path we defined, we will see the events tick once a second, and see the stock price
represented as a JSON string. We’ve created a simple Kotlin Spring Boot application that uses Reactive Streams to
emit a randomly generated stock price once a second. In the rest of the tutorial we’ll show how
to connect to this server to retrieve prices, and how to create a chart that shows the price
updates in real time. Thanks for watching!

Leave a Reply

Your email address will not be published. Required fields are marked *