Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Microservices Deployment Cookbook

You're reading from   Microservices Deployment Cookbook Deploy and manage scalable microservices

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781786469434
Length 378 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vikram Murugesan Vikram Murugesan
Author Profile Icon Vikram Murugesan
Vikram Murugesan
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Building Microservices with Java FREE CHAPTER 2. Containerizing Microservices with Docker 3. Deploying Microservices on Mesos 4. Deploying Microservices on Kubernetes 5. Service Discovery and Load Balancing Microservices 6. Monitoring Microservices 7. Building Asynchronous Streaming Systems with Kafka and Spark 8. More Clustering Frameworks - DC/OS, Docker Swarm, and YARN

Writing microservices with Spring Boot

Now that our project is ready, let's look at how to write our microservice. There are several Java-based frameworks that let you create microservices. One of the most popular frameworks from the Spring ecosystem is the Spring Boot framework. In this recipe, we will look at how to create a simple microservice application using Spring Boot.

Getting ready

Any application requires an entry point to start the application. For Java-based applications, you can write a class that has the main method and run that class as a Java application. Similarly, Spring Boot requires a simple Java class with the main method to run it as a Spring Boot application (microservice). Before you start writing your Spring Boot microservice, you will also require some Maven dependencies in your pom.xml file.

How to do it...

  1. Create a Java class called com.packt.microservices.geolocation.GeoLocationApplication.java and give it an empty main method:
            package com.packt.microservices.geolocation;  
              public class GeoLocationApplication {  
                public static void main(String[] args) { 
                // left empty intentionally 
               } 
              } 
    
  2. Now that we have our basic template project, let's make our project a child project of Spring Boot's spring-boot-starter-parent pom module. This module has a lot of prerequisite configurations in its pom.xml file, thereby reducing the amount of boilerplate code in our pom.xml file. At the time of writing this, 1.3.6.RELEASE was the most recent version:
            <parent> 
              <groupId>org.springframework.boot</groupId> 
              <artifactId>spring-boot-starter-parent</artifactId> 
              <version>1.3.6.RELEASE</version> 
            </parent> 
    
  3. After this step, you might want to run a Maven update on your project as you have added a new parent module. If you see any warnings about the version of the maven-compiler  plugin, you can either ignore it or just remove the <version>3.5.1</version> element. If you remove the version element, please perform a Maven update afterward.
  4. Spring Boot has the ability to enable or disable Spring modules such as Spring MVC, Spring Data, and Spring Caching. In our use case, we will be creating some REST APIs to consume the geolocation information of the users. So we will need Spring MVC. Add the following dependencies to your pom.xml file:
            <dependencies> 
              <dependency> 
                <groupId>org.springframework.boot</groupId> 
                <artifactId>spring-boot-starter-web</artifactId> 
              </dependency> 
            </dependencies> 
    
  5. We also need to expose the APIs using web servers such as Tomcat, Jetty, or Undertow. Spring Boot has an in-memory Tomcat server that starts up as soon as you start your Spring Boot application. So we already have an in-memory Tomcat server that we could utilize.
  6. Now let's modify the GeoLocationApplication.java class to make it a Spring Boot application:
            package com.packt.microservices.geolocation; 
            import org.springframework.boot.SpringApplication; 
            import org.springframework.boot.autoconfigure
             .SpringBootApplication; 
              @SpringBootApplication 
              public class GeoLocationApplication { 
                public static void main(String[] args) {
                SpringApplication.run(GeoLocationApplication.class, args); 
               } 
              } 
    

As you can see, we have added an annotation, @SpringBootApplication, to our class. The @SpringBootApplication annotation reduces the number of lines of code written by adding the following three annotations implicitly:

  • @Configuration
  • @ComponentScan
  • @EnableAutoConfiguration

If you are familiar with Spring, you will already know what the first two annotations do. @EnableAutoConfiguration is the only annotation that is part of Spring Boot. The AutoConfiguration package has an intelligent mechanism that guesses the configuration of your application and automatically configures the beans that you will likely need in your code.

You can also see that we have added one more line to the main method, which actually tells Spring Boot the class that will be used to start this application. In our case, it is GeoLocationApplication.class. If you would like to add more initialization logic to your application, such as setting up the database or setting up your cache, feel free to add it here.

  1. Now that our Spring Boot application is all set to run, let's see how to run our microservice. Right-click on GeoLocationApplication.java from Package Explorer, select Run As, and then select Spring Boot App. You can also choose Java Application instead of Spring Boot App. Both the options ultimately do the same thing. You should see something like this on your STS console:

    How to do it...

  2. If you look closely at the console logs, you will notice that Tomcat is being started on port number 8080. In order to make sure our Tomcat server is listening, let's run a simple curl command. cURL is a command-line utility available on most Unix and Mac systems. For Windows, use tools such as Cygwin or even Postman. Postman is a Google Chrome extension that gives you the ability to send and receive HTTP requests. For simplicity, we will use cURL. Execute the following command on your terminal:
          curl http://localhost:8080
    
  3. This should give us an output like this:
          {"timestamp":1467420963000,"status":404,"error":"Not
          Found","message":"No message available","path":"/"}
    
    

This error message is being produced by Spring. This verifies that our Spring Boot microservice is ready to start building on with more features. There are more configurations that are needed for Spring Boot, which we will perform later in this chapter along with Spring MVC.

You have been reading a chapter from
Microservices Deployment Cookbook
Published in: Jan 2017
Publisher: Packt
ISBN-13: 9781786469434
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $24.99/month. Cancel anytime