Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Microservices Deployment Cookbook
Microservices Deployment Cookbook

Microservices Deployment Cookbook: Deploy and manage scalable microservices

By Vikram Murugesan
€32.99 €22.99
Book Jan 2017 378 pages 1st Edition
eBook
€32.99 €22.99
Print
€41.99
Subscription
€14.99 Monthly
eBook
€32.99 €22.99
Print
€41.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 31, 2017
Length 378 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786469434
Category :
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Microservices Deployment Cookbook

Chapter 1. Building Microservices with Java

In this chapter, we will cover the following recipes:

  • Creating a project template using STS and Maven

  • Writing microservices with Spring Boot

  • Writing REST APIs with Spring MVC

  • Writing microservices with WildFly Swarm

  • Writing microservices with Dropwizard

  • Writing REST APIs with SparkJava

Microservices have gained a lot of traction recently. A microservice-based architecture is one way of designing your software. In such an architecture, applications are broken down into smaller services so that they can be deployed and managed separately. This takes away a lot of pain points that occur in traditional monolithic applications. With that being said, microservices can be built using any programming language. In fact, there are many libraries and frameworks that help programmers build microservices using Java, Scala, C#, JavaScript, Python, Ruby, and so on. In this book, we will focus more on building and deploying microservices with Java.

Introduction


In a traditional microservice-based design, monolithic applications will be broken down into smaller services that can talk to other services either in a synchronous or asynchronous model, based on the need and use case. The first question that anyone would have when breaking down monolithic applications is "what are the potential services that my application can be broken down into?" There is no rule of thumb or straight-forward answer to this. But usually, one looks for independent functionalities. Each and every functionality can be considered to be built as its own service.

To illustrate this, let's take a look at an example application and see how it could be broken down into smaller, manageable and deployable microservices. The sample application we will be looking at is a biker tracking application. This application will have the following functionalities:

  • Web interface to monitor the user's progress on a map

  • REST API to consume the user's geolocation data constantly

  • Analytics code to perform calculations for biking route suggestions, weather predictions, biking gear suggestions, calories burnt, water intake, and so on

Let's take a look at how this application might have been designed as a monolithic application:

As you can see, the whole application is bundled as one artifact and therefore promotes a single point of failure (SPOF). If for some reason the analytics code crashes your JVM, we will lose the web interface, REST APIs, and analytics as a whole. Now, let's take a look at how this might be broken down into manageable microservices:

In this architecture diagram, you can see that each and every functionality is deployed as its own microservice. The service implementations have been broken down into a Notification Service, which will take care of sending notifications to the users, and the Geo Location Tracker Service, which keeps track of the geolocation (latitude and longitude) information of all the users. The Analytics code has been broken down into its own microservices. So if one type of analytics microservice goes down, the other microservices will keep functioning properly. You might have noticed that the REST APIs are missing. They are actually not missing, but integrated into their respective microservices.

Now let's not waste any more time and jump directly into building one part of this application. To be able to illustrate the extensive concepts that this book offers, I have chosen the geolocation tracker service as our example microservice. This service will be responsible for collecting the geolocation of all users of this application and then storing them in a data store.

Creating a project template using STS and Maven


Creating a project for your microservice is no different than creating a simple Java project. We will use Maven as our build framework as it is considered to be one of the most popular build frameworks. If you are comfortable using other frameworks, such as Gradle, SBT, or Ivy, feel free to use them. But keep in mind that the recipes throughout this book will use Maven extensively. Unless you are an expert in your preferred framework, I strongly recommend using Maven.

Getting ready

In order to create your microservice project, you will need the following software. Follow the instructions on their respective websites to install them:

  • JDK 1.8+

  • Maven 3.3.9+

  • Spring Tool Suite (STS) 3.8.0+

Make sure both Java and Maven are in your PATH variable so that you can use the java and mvn commands on every terminal shell without having to set PATH each time. Spring Tool Suite is a sophisticated version of Eclipse that has lot of Spring plugins and extensions. If you are familiar with other IDEs, feel free to use them. But for familiarity, this book will use STS for all recipes.

How to do it...

After you have installed the above-mentioned software, open Spring Tool Suite. The first time you open it, you will be requested to choose a workspace. Go ahead and enter your workspace location. In this recipe, we will learn how to create a template Maven project using STS and Maven. STS comes with Maven Integration out of the box. So we don't have to configure it any further. After your STS IDE has completed startup, follow the below instructions to create a new Maven project:

  1. In your STS window, right-click anywhere on the Package Explorer, select New, and then select Maven Project, as shown in the following screenshot:

  2. This will open a popup that will let you chose the type of Maven project you would like to create. We will skip the archetype selection by checking the box that says Create a simple project (skip archetype selection) and then hit Next:

  3. In the next window, enter the following details to create your project:

    • Group Id: com.packt.microservices

    • Artifact Id: geolocation

    • Name: geolocation

  4. After you have entered the details, hit Finish:

  5. This will create a simple Maven JAR module with all the required directories in place. Depending on your IDE settings, STS configures your new project with the default Java version. If you have not set any defaults, it will configure your project with Java 1.5. You can verify this by checking your project structure in STS. The following screenshot shows that STS uses Java 1.5 for your project:

  6. We will use Java 8's lambda expressions in other chapters. So let's change the Java version from 1.5 to 1.8. In order to change the Java version, we will configure the maven-compiler-plugin in the pom.xmlfile. Add the following section of code to your pom.xml file's project section:

            <build> 
              <plugins> 
               <plugin> 
                  <groupId>org.apache.maven.plugins</groupId> 
                  <artifactId>maven-compiler-plugin</artifactId> 
                <version>3.5.1</version> 
                <configuration> 
                  <source>1.8</source> 
                  <target>1.8</target> 
                </configuration> 
               </plugin> 
             </plugins> 
            </build> 
    
  7. Save your pom.xml file, right-click on your project, choose Maven, and then hit Update Project... or use the keyboard shortcut Alt + F5. This will automatically change your project's Java version to 1.8.

  8. Our microservice project is now ready to play with.

There's more...

If you are more comfortable using the command line to create Maven projects, issue the following command in your terminal to create the new project:

mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes \
-DgroupId=com.packt.microservices -DartifactId=geolocation \ 
-Dname=geolocation

After Maven creates the project, you should be able to import your project into your IDE. As this is something out of the scope of this book, we will not be looking at how to import an existing Maven project into your IDE.

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:

  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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Adopt microservices-based architecture and deploy it at scale
  • Build your complete microservice architecture using different recipes for different solutions
  • Identify specific tools for specific scenarios and deliver immediate business results, correlate use cases, and adopt them in your team and organization

Description

This book will help any team or organization understand, deploy, and manage microservices at scale. It is driven by a sample application, helping you gradually build a complete microservice-based ecosystem. Rather than just focusing on writing a microservice, this book addresses various other microservice-related solutions: deployments, clustering, load balancing, logging, streaming, and monitoring. The initial chapters offer insights into how web and enterprise apps can be migrated to scalable microservices. Moving on, you’ll see how to Dockerize your application so that it is ready to be shipped and deployed. We will look at how to deploy microservices on Mesos and Marathon and will also deploy microservices on Kubernetes. Next, you will implement service discovery and load balancing for your microservices. We’ll also show you how to build asynchronous streaming systems using Kafka Streams and Apache Spark. Finally, we wind up by aggregating your logs in Kafka, creating your own metrics, and monitoring the metrics for the microservice.

What you will learn

[*] Build microservices using Spring Boot, Wildfly Swarm, Dropwizard, and SparkJava [*] Containerize your microservice using Docker [*] Deploy microservices using Mesos/Marathon and Kubernetes [*] Implement service discovery and load balancing using Zookeeper, Consul, and Nginx [*] Monitor microservices using Graphite and Grafana [*] Write stream programs with Kafka Streams and Spark [*] Aggregate and manage logs using Kafka [*] Get introduced to DC/OS, Docker Swarm, and YARN

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 31, 2017
Length 378 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786469434
Category :
Concepts :

Table of Contents

15 Chapters
Microservices Deployment Cookbook Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Customer Feedback Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Building Microservices with Java Chevron down icon Chevron up icon
2. Containerizing Microservices with Docker Chevron down icon Chevron up icon
3. Deploying Microservices on Mesos Chevron down icon Chevron up icon
4. Deploying Microservices on Kubernetes Chevron down icon Chevron up icon
5. Service Discovery and Load Balancing Microservices Chevron down icon Chevron up icon
6. Monitoring Microservices Chevron down icon Chevron up icon
7. Building Asynchronous Streaming Systems with Kafka and Spark Chevron down icon Chevron up icon
8. More Clustering Frameworks - DC/OS, Docker Swarm, and YARN Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.