Cloud-Native Applications in Java
eBook - ePub

Cloud-Native Applications in Java

Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar

Condividi libro
  1. English
  2. ePUB (disponibile sull'app)
  3. Disponibile su iOS e Android
eBook - ePub

Cloud-Native Applications in Java

Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Cloud-Native Applications in Java è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Cloud-Native Applications in Java di Ajay Mahajan, Munish Kumar Gupta, Shyam Sundar in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatica e Linguaggi di programmazione. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781787128842
Edizione
1
Argomento
Informatica

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 
    ...

Indice dei contenuti