Cloud-Native Applications in Java
eBook - ePub

Cloud-Native Applications in Java

Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar

Share book
  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Cloud-Native Applications in Java

Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar

Book details
Book preview
Table of contents
Citations

About This Book

Highly available microservice-based web apps for Cloud with JavaAbout This Book• Take advantage of the simplicity of Spring to build a full-fledged application• Let your applications run faster while generating smaller cloud service bills• Integrate your application with various tools such as Docker and ElasticSearch and use specific tools in Azure and AWSWho This Book Is ForJava developers who want to build secure, resilient, robust and scalable applications that are targeted for cloud based deployment, will find this book helpful. Some knowledge of Java, Spring, web programming and public cloud providers (AWS, Azure) should be sufficient to get you through the book.What You Will Learn• See the benefits of the cloud environment when it comes to variability, provisioning, and tooling support• Understand the architecture patterns and considerations when developing on the cloud• Find out how to perform cloud-native techniques/patterns for request routing, RESTful service creation, Event Sourcing, and more• Create Docker containers for microservices and set up continuous integration using Jenkins• Monitor and troubleshoot an application deployed in the cloud environment• Explore tools such as Docker and Kubernetes for containerization and the ELK stack for log aggregation and visualization• Use AWS and Azure specific tools to design, develop, deploy, and manage applications• Migrate from monolithic architectures to a cloud native deploymentIn DetailBusinesses today are evolving so rapidly that they are resorting to the elasticity of the cloud to provide a platform to build and deploy their highly scalable applications. This means developers now are faced with the challenge of building build applications that are native to the cloud. For this, they need to be aware of the environment, tools, and resources they're coding against.If you're a Java developer who wants to build secure, resilient, robust, and scalable applications that are targeted for cloud-based deployment, this is the book for you. It will be your one stop guide to building cloud-native applications in Java Spring that are hosted in On-prem or cloud providers - AWS and AzureThe book begins by explaining the driving factors for cloud adoption and shows you how cloud deployment is different from regular application deployment on a standard data centre. You will learn about design patterns specific to applications running in the cloud and find out how you can build a microservice in Java Spring using REST APIsYou will then take a deep dive into the lifecycle of building, testing, and deploying applications with maximum automation to reduce the deployment cycle time. Gradually, you will move on to configuring the AWS and Azure platforms and working with their APIs to deploy your application. Finally, you'll take a look at API design concerns and their best practices. You'll also learn how to migrate an existing monolithic application into distributed cloud native applications.By the end, you will understand how to build and monitor a scalable, resilient, and robust cloud native application that is always available and fault tolerant.Style and approachFilled with examples, this book will build you an entire cloud-native application through its course and will stop at each point and explain in depth the functioning and design considerations that will make a robust, highly available application

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Cloud-Native Applications in Java an online PDF/ePUB?
Yes, you can access Cloud-Native Applications in Java by Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar in PDF and/or ePUB format, as well as other popular books in Informatica & Linguaggi di programmazione. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781787128842

Extending Your Cloud-Native Application

Having understood the design principles, let's take the skeleton services developed in Chapter 2, Writing Your First Cloud-Native Application, and do some real work on them to make them production-ready.
We defined two get services; getProduct for a given a product ID, and getProducts for a given category. These two services have highly non-functional requirements. They always have to be available and serve the data with the lowest possible latency. The following steps will take us there:
  1. Accessing data: Service access to data across various resources
  2. Caching: Options to do caching and their considerations
  3. Applying CQRS: Enable us to have different data models to service different requests
  4. Error handling: How to recover, what return codes to send, and implementation of patterns such as a circuit breaker
We will also look at adding methods to modify the data, such as insert, update, and delete. In this chapter, we will cover:
  • Validations: Ensuring that the data is clean before being processed
  • Keeping two models of CQRS in sync: For data consistency
  • Event driven and asynchronous updates: How it scales the architecture and decouples it at the same time

Implementing the get services

Let's take our product project developed in Chapter 2, Writing Your First Cloud-Native Application, forward. We will incrementally enhance it while discussing the concepts.
Let's think carefully about the database of our two services. getProduct returns the product information, while getProducts searches a list of products that fall into this category. To begin with, for simple and standard requirements, both queries can be answered by a single data model in a relational database:
  1. You would store a product in a product table with a fixed number of columns.
  2. You would then index the category so that the queries against it can run quickly.
Now, this design will be fine for most requirements for an average-sized company.

Simple product table

Let's use a product table in a standard relational database and access it in our service using Spring Data. Spring Data provides excellent abstractions to use the Java Persistence API (JPA) and makes coding data access objects (DAO) much easier. Spring Boot further helps in writing minimal code to begin with and extending it as we go ahead.
Spring Boot can work with embedded databases, such as H2, HSQLDB, or the external database. In-process embedded database starts with our Java service in a process and then terminates when the process dies. This is fine to begin with. Later on, the dependencies and URLs can be changed to point to actual databases.
You can take the project from Chapter 2, Writing Your First Cloud-Native Application, and add the following steps, or just download the completed code from GitHub (https://github.com/PacktPublishing/Cloud-Native-Applications-in-Java):
  1. Maven POM: Including POM dependencies:
This will tell Spring Boot to include the Spring Boot starter JPA and use HSQLDB in embedded mode.
  1. Entity: As per the JPA, we will start using the concept of entity. We already have a domain object named Product from our previous project. Refactor it to put in an entity package. Then, add the notations of @Entity, @Id, and @Column, as shown in the following Product.java file:
package com.mycompany.product.entity ; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Product { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id ; @Column(nullable = false) private String name ; @Column(nullable = false) private int catId ; 
The rest of the code, such as constructors and getters/setters, remains the same.
  1. Repository: Spring Data provides a repository, which is like a DAO class and provides methods to do Create, Read, Update, and Delete (CRUD) operations on the data. A lot of standard operations are already provided in the CrudRepository interface. We will be using only the query operations from now on.
    In our case, since our domain entity is Product, the repository will be ProductRepository, which extends Spring's CrudRepository, and manages the Product entity. During extension, the entity and the data type of the primary key needs to be specified using generics, as shown in the following ProductRepository.java file:
package com.mycompany.product.dao; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.mycompany.product.entity.Product; public interface ProductRepository extends CrudRepository<Product, Integer> { List<Product> findByCatId(int catId); } 
The first question that would come to mind is whether this code is sufficient enough to work. It has just one interface definition. How can it be enough to handle our two methods, namely getProduct (given a product ID) and getProducts (for a given category)?
The magic happens in Spring Data, which helps with the boilerplate code. The CrudRepository interface comes with a set of default methods to implement the most common operations. These include save, delete, find, count, and exists operations which suffice for most of the query and update tasks. We will look at the update operations in the second half of this chapter, but let's focus on the query operations first.
The operation of finding a product given an ID is already present in the CrudRepository as a findOne method. Hence, we do not need to call it explicitly.
The task of finding products for a given category is done by the findByCatId method in our ProductRepository interface. The query builder mechanism built into the Spring Data repository infrastructure is useful for building queries over entities of the repository. The mechanism strips the prefixes, such as find, read, query, count, and get from the method and starts parsing the rest of it based on the entity. This mechanism is very powerful because the choice of keywords and the combinations means the method name is enough to do most of the query operations including operators (and/or) distinct clauses, and so on. Do refer to the Spring Data reference documentation (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/) to see the details.
These conventions allow Spring Data and Spring Boot to inject implementations of the methods based on parsing the interfaces.
  1. Changing the service: In Chapter 2, Writing Your First Cloud-Native Application, our product service was returning dummy hard-coded data. Let's change it to something useful that goes against the database. We achieve this by using the ProductRepository interface that we defined earlier, and injecting it through @Autowiring annotation into our ProductService class, as shown in the following ProductService.java file:
@RestController public class ProductService { @Autowired ProductRepository prodRepo ; @RequestMapping("/product/{id}") Product getProduct(@PathVariable("id") int id) { return prodRepo.findOne(id); } @RequestMapping("/products") List<Product> getProductsForCategory(@RequestParam("id") int id) { return prodRepo.findByCatId(id); } } 
The findOne method from the repository gets the object given a primary key, and the findByCatId method we defined helps to find products given a category.
  1. Schema definition: For now, we will leave the schema creation to the hibernate capability to auto generate a script. Since we do want to see what script got created, let's enable logging for the classes as follows in the application.properties file:
logging.level.org.hibernate.tool.hbm2ddl=DEBUG logging.level.org.hibernate.SQL=DEBUG 
    ...

Table of contents