Spring Boot Microservices—Examples to Help You Get Started
Tags: microservices, coding, programming
Published: 2019-10-01 13:38:32

<!-- wp:paragraph -->
<p>It can feel daunting to build a new microservice. It feels like there are a lot of things to keep in mind. Fortunately, Spring has a variety of libraries that can get us started quickly. We can focus on the bits that matter to us and let Spring scaffold the rest. In this post, we're going to take a look at what makes microservices different from other types of applications and how Spring helps us get up and running fast.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":2134,"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://library.scalyr.com/2019/01/14222838/Spring-Boot-microservices-with-Scalyr-colors.png" alt="" class="wp-image-2134"/></figure></div>
<!-- /wp:image -->

<!-- wp:more -->
<!--more-->
<!-- /wp:more -->

<!-- wp:heading -->
<h2>What Do We Mean by "Microservice"?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>So, what exactly do we mean when we talk about microservices? They have their origins in a very specific type of service. It's not just any deployment artifact. In Martin Fowler's <a href="https://martinfowler.com/articles/microservices.html">article about microservices</a>,&nbsp;he mentions a few key characteristics that separate microservices from just another deployed app:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Componentization via services.</li><li>Organized around business capabilities.</li><li>Products, not projects.</li><li>Decentralized data management.</li><li>Design for failure.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>We're going to take a look at which Spring libraries help us achieve these characteristics. But before that, let's talk about how we can easily set up a new microservice with any set of libraries.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Spring Initializr, Our Launchpad</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You're about to find out just how overwhelming the amount&nbsp;of Spring libraries that exist for building microservices is. Fortunately, there are two great tools to help us in our path. The first is&nbsp;<a href="https://start.spring.io">Spring Initializr.</a>&nbsp;This little site will get you up and running with a new Spring project in minutes, along with all the components you want to use.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The second tool is the website&nbsp;<a href="https://www.baeldung.com/">Baeldung</a>, which is chock-full of in-depth Spring tutorials on all of the libraries we'll be using. You can use this site to dive deeper to any library for interest. They also have open-source code examples for their tutorials, from which we will be borrowing.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, onto the libraries.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Componentization Via Services</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Componentizing into services is the idea that a microservice is independently&nbsp;deployable and runnable. In this vein, let's look at libraries that help us start up our application.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Spring Boot</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's start with the foundation of everything: Spring Boot. This library is the basis of almost every other Spring library out there. Spring Boot sets up our application context, wiring up all our software components It also makes it really easy to execute our JAR—our software package—as a console application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To include Spring Boot in your project, use Spring Initializr or add the following:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">buildscript {
   ext {
      //This is the most recent version at the time of writing. 
      springBootVersion = '2.1.1.RELEASE'
   }
   dependencies {
      //This makes the jar executable.
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
...
apply plugin: 'org.springframework.boot'
//This makes it easier to manage the correct versions of the Spring libraries. The bill of materials ensures the versions are compatible with each other.
apply plugin: 'io.spring.dependency-management'
...
repositories {
	mavenCentral()
        //Some of the libraries we discuss are stored in the milestones repository.
	maven { url "https://repo.spring.io/milestone" }
}
...
dependencies {
   //This let's our code sping up a Spring ApplicationContext in our Main method
   implementation('org.springframework.boot:spring-boot-starter')
   //This gives us some unit testing utilities and runners
   testImplementation('org.springframework.boot:spring-boot-starter-test')
}
...
dependencyManagement {
 imports {
    //This is the actual bill of materials for spring dependencies
    mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
 }
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>For the examples in this post, I'll be using Gradle for dependency management, but you can also use Maven. Spring Initializr supports both.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>With our dependencies in place, our application main method can look&nbsp;like this:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>And that's all you need to get started! Note, however, that there's a lot more functionality built into Spring Boot than this;<a href="https://spring.io/projects/spring-boot">&nbsp;explore it</a> at your leisure.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Organized Around Business Capabilities</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Microservices should be aligned only with business concepts like ordering, fulfillment, shipping, and customer service. They shouldn't be centered around concepts like data access, authentication, or email. Spring doesn't directly help with figuring out proper business boundaries. In fact, this is probably one of the hardest aspects of creating healthy microservices, and it's out of scope for this article. However, once you figure out your boundaries, Spring provides some libraries that will let you expose this functionality to your customers.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Web</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Spring Web is a classic library that allows us to serve up both web pages and HTTP endpoints to our users. It also spins up an embedded Tomcat web server and binds to a port, so we can talk to the wider world.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The web dependency will look like this:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
        //This can replace the "spring-boot-starter" dependency from above. 
	implementation('org.springframework.boot:spring-boot-starter-web')
	...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>With that in place, we can build HTTP endpoints:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@Controller
public class SimpleController {

    @GetMapping("api/hello")
    public String homePage() {
        return "hello";
    }
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>If I GET /hello with curl or<a href="https://www.getpostman.com/"> Postman</a>, I'll see a response with "hello" as the only content.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are loads more capabilities with Spring Boot Web. What I have shown here just barely scratches the surface. You'll have the ability to add security, deal with exceptions, add request/response middleware, and much more. Try out <a href="https://www.baeldung.com/spring-boot-start">some tutorials on it</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Alternatives</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Spring has a newer variant of building web apps called Spring <a href="https://www.baeldung.com/spring-webflux">WebFlux</a>. This variant aims to be more <a href="https://www.reactivemanifesto.org/">reactive</a> and to more easily support asynchronous, scalable operations.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Products, Not Projects</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Products over projects is the spirit of DevOps. You build it, you run it. You can't just deploy a microservice into the ether—you have to monitor it and maintain it. Spring has a couple of libraries that can help us not only build but also run our microservices.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":5454} -->
<figure class="wp-block-image"><img src="https://library.scalyr.com/2019/10/01063427/Copy-of-Copy-of-Copy-of-TEMPLATE-.png" alt="" class="wp-image-5454"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Actuator</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You set it up like so:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
   implementation('org.springframework.boot:spring-boot-starter-actuator')
   ...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>By default, only the /actuator/info and /health endpoints are enabled. You can enable all endpoints in your property file with:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">management.endpoints.web.exposure.include=*</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>There are many endpoints in Actuator, and I recommend <a href="https://docs.spring.io/spring-boot/docs/2.0.x/actuator-api/html/">exploring them all</a>. You can also see them through the /actuator endpoint. My favorite is /actuator/metrics. Its response looks something like this:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">{
  "names" : [ "jvm.memory.max", "jvm.memory.used", "jvm.memory.committed", "jvm.buffer.memory.used", "jvm.buffer.count", "jvm.buffer.total.capacity" ]
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>If you drill into a specific one, such as /actuator/metrics/jvm.memory.max, you can see something like this:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">{
  "name" : "jvm.memory.max",
  "description" : "The maximum amount of memory in bytes that can be used for memory management",
  "baseUnit" : "bytes",
  "measurements" : [ {
    "statistic" : "VALUE",
    "value" : 2.384986111E9
  } ],
  "availableTags" : [ {
    "tag" : "area",
    "values" : [ "heap", "nonheap" ]
  }, {
    "tag" : "id",
    "values" : [ "Compressed Class Space", "PS Survivor Space", "PS Old Gen", "Metaspace", "PS Eden Space", "Code Cache" ]
  } ]
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>This immediately gives you a level of insight into your latency, error rates, and so on. You can also customize existing or new actuator endpoints as you desire.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Sleuth</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>It's highly likely that our microservices aren't running in isolation. At the end of the day, they have to communicate with queues, databases, and even other microservices to do their job fully. When things go wrong, it can be hard to track all the work that has happened in a request. If I want to be able to quickly debug issues across multiple deployed services, I need some tooling. Spring Sleuth lets us trace these requests across microservice boundaries. It can even let us trace to database calls.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We add it like so:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
   implementation('org.springframework.cloud:spring-cloud-starter-sleuth')
   ...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>After this, we technically don't need to wire up any more code. It works with other Spring libraries to add tracing context when calling other services and databases. You can see this context when you log:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">2018-01-10 22:36:38.254  INFO 
  [Microservice Starter,4e30f7340b3fb631,4e30f7340b3fb631,false] 12516 
  --- [nio-8080-exec-1] c.b.spring.session.SleuthController : Hello Sleuth</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>The first GUID is the trace ID, which is the same across the request. The next GUID is the span ID, which represents the current unit of work. Having this context lets us query and group our log messages in a way that lets us see the life cycle of a request. You can also report these traces to external storage, but that is outside the scope of this article. Read <a href="https://www.baeldung.com/spring-cloud-sleuth-single-application">this article</a> by Baeldung for more information.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Decentralized Data Management</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A microservice should own its data through and through and have minimal coupling to another service's data. No one else should be able to access its data directly.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>JPA With SQL Server</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Spring makes it easy for a <a href="https://www.scalyr.com/blog/microservices-logging-best-practices-2/">microservice</a> to own its own data for multiple data stores. Using the Spring JPA library lets us use Hibernate and the JPA specification to interact with a relational database like SQL Server.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can wire it up like this:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
	implementation('org.springframework.boot:spring-boot-starter-data-jpa')
	runtimeOnly('com.microsoft.sqlserver:mssql-jdbc')
        ...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>You then enable it in your application or an @Configuration:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@EnableJpaRepositories("org.scalyr.persistence.repo") 
@EntityScan("org.scalyr.persistence.model")
@SpringBootApplication
public class Application {
   ...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>Then we can map our classes to database tables:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@Entity
public class Book {
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
 
    @Column(nullable = false, unique = true)
    private String title;
 
    @Column(nullable = false)
    private String author;
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>and use Spring repositories to work with the data:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">public interface BookRepository extends CrudRepository&lt;Book, Long&gt; {
    List&lt;Book&gt; findByTitle(String title);
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>For more information, check out <a href="https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa">this tutorial.</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Cloud Stream With Rabbit</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Decentralizing data is a powerful way to keep <a href="https://www.scalyr.com/blog/microservices-vs-soa-whats-the-difference/">microservices </a>autonomous, but it's inevitable that some of this data will need to be shared across services. We don't want to share our databases, and we want to avoid runtime coupling on other services when possible. After all, we can't count on those services always being up and running. We can have our cake and eat it, too, by sharing data through<a href="https://microservices.io/patterns/data/saga.html"> event-driven messaging.</a>&nbsp;Spring Cloud Stream with RabbitMQ makes this relatively easy to do.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can add the dependencies as so:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
	implementation('org.springframework.cloud:spring-cloud-starter-stream-rabbit')
	testImplementation('org.springframework.cloud:spring-cloud-stream-test-support')
}
</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>Then we can publish and subscribe to messages through Rabbit queues in our application:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@SpringBootApplication
@EnableBinding(Processor.class)
public class MyLoggerServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyLoggerServiceApplication.class, args);
    }
 
    @StreamListener(Processor.INPUT)
    @SendTo(Processor.OUTPUT)
    public LogMessage enrichLogMessage(LogMessage log) {
        return new LogMessage(String.format("[1]: %s", log.getMessage()));
    }
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>INPUT and OUTPUT are built-in channels that let us specify from where we subscribe to messages and to where we publish them. We need to bind Rabbit to these channels:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">spring:
  cloud:
    stream:
      bindings:
        input:
          destination: queue.log.messages
          binder: local_rabbit
          group: logMessageConsumers
        output:
          destination: queue.pretty.log.messages
          binder: local_rabbit
      binders:
        local_rabbit:
          type: rabbit
          environment:
            spring:
              rabbitmq:
                host: localhost
                port: 5672
                username: guest
                password: guest
                virtual-host: /
server:
  port: 0
management:
  health:
    binders:
       enabled: true</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>The application code remains blissfully ignorant of the specific transportation being used to publish or receive messages—we push all of that to the above configuration. You can see that we bound the INPUT and OUTPUT channels to specific exchanges in Rabbit. These exchanges and queues are automatically declared for us by the Cloud Stream Rabbit library. For more information, check out <a href="https://www.baeldung.com/spring-cloud-stream">this article</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Alternatives</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Spring also has support for NoSQL databases, like MongoDB. Spring supports just about any popular persistence mechanism. If using Cloud Stream support, we can use Kafka instead of RabbitMQ.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Design for Failure</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>When dealing with distributed, autonomous services, we can't count on them being up at all times. When communicating with other services, we should be ready to handle the inevitable.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Hystrix</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Netflix built a library called Hystrix that lets us apply the <a href="https://martinfowler.com/bliki/CircuitBreaker.html">circuit breaker pattern</a> when communicating with other services. Using circuit breakers when communicating externally gives us a measure of resiliency to system outages. We can fall back to a default behavior when the service with which we want to communicate is unavailable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The dependency is:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
	implementation('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>The configuration is dead simple:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@HystrixCommand(
  commandKey = "ratingsByIdFromDB", 
  fallbackMethod = "findCachedRatingById", 
  ignoreExceptions = { RatingNotFoundException.class })
public Rating findRatingById(Long ratingId) {
    return Optional.ofNullable(ratingRepository.findOne(ratingId))
      .orElseThrow(() -&gt; 
        new RatingNotFoundException("Rating not found. ID: " + ratingId));
}
 
public Rating findCachedRatingById(Long ratingId) {
    return cacheRepository.findCachedRatingById(ratingId);
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>You can see that if the repository call fails, we can use a cached version. Feel free to <a href="https://www.baeldung.com/spring-cloud-netflix-hystrix">read more here</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Retry</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In many cases, circuit breaking may be a bit of overkill. Often we have intermittent network failures that we can overcome with a simple retry. Enter Spring Retry.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We add it to our Gradle build with:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">dependencies {
	implementation('org.springframework.retry:spring-retry'))
        ...
}
</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>We then enable it via:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@Configuration
@EnableRetry
public class AppConfig { ... }</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>And we implement it with:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">@Service
public interface MyService {
    @Retryable(
      value = { SQLException.class }, 
      maxAttempts = 2,
      backoff = @Backoff(delay = 5000))
    void retryService(String sql) throws SQLException;
    ...
}</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>This says, "Please retry 'retryService' up to two times if you see an SQLException, and wait 5,000 ms between each retry."</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>... And Many More</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As you can see, Spring provides a myriad of libraries we can use to get a large boost into building microservices. We have much of what we need, from providing APIs to accessing data and even monitoring our application once it's in production. There are many more libraries you can use for more advanced use cases, so go out and explore using Spring for your own microservices.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Want to read more about Spring? <a href="https://www.scalyr.com/blog/get-started-quickly-with-spring-boot-logging/">We covered it in our "getting started quickly with logging" series</a>, so head there next!</p>
<!-- /wp:paragraph -->