Starting a microservice with Scala
17 Feb 2017A microservice is an architectural pattern that allows your services to deployed in an isolated fashion. This isolation allows your service to remain focused on its problem (and only its problem) that its trying to solve, as well as simplify telemetry, instrumentation, and measurement metrics. From Martin Fowler’s site:
The term “Microservice Architecture” has sprung up over the last few years to describe a particular way of designing software applications as suites of independently deployable services. While there is no precise definition of this architectural style, there are certain common characteristics around organization around business capability, automated deployment, intelligence in the endpoints, and decentralized control of languages and data.
If you want to learn more about microservices, seriously, check out google. They’re everywhere!
The purpose of today’s article is to stand a microservice up in Scala, to get up and running quickly.
Getting started
In a previous article, I showed you how you can create a scala project structure with a shell script. We’ll use that right now to create our project microservice-one.
Dependencies
Now we’ll need to sort out our dependencies.
We’ll need scalatest for testing, akka and akka-http to help us make our API concurrent/parallel as well as available over HTTP. Our build.sbt
file should look like this:
Update our project now:
The code
We’re going to dump everything into one file today; the main application object. All of the parts are very descriptive though and I’ll go through each one. Our microservice is going to have one route, which is a GET on /greeting
. It’ll return us a simple message.
First up, we model how the message will look:
Using this case class
, you’d expect messages to be returned that look like this:
We tell the application how to serialize this data over the http channel using Protocols
:
Now, we can put together our actual service implementation. Take a look specifically at the DSL that scala is provided for route definition:
So, our one route here will constantly just send out “Hello to you!”.
Finally, all of this gets hosted in our main application object:
That’s it for the code. In the src/main/resources
directory, we’ll put a application.conf
file that details a few configurations for us:
Running
Lets give it a run now.
Once SBT has finished its dirty work, you’ll be able to request your route at http://localhost:3000/greeting:
Perfect.
That’s all for today.