You are on page 1of 43

What is Microservice?

developed based on business features and deployed independently by

an automated deployment machinery.

There is less centralized management of Microservices that may be written in various


programming languages and utilize diverse data storage technologies.

For example: In an ecommerce site, Payment service could be written in C++, while Order
management service could be written in Java.

DID YOU KNOW - Amazon is regarded as the first company to get microservices and APIs right.

comunication: rest http / mensajes state less - lose couple, smort parts, interface can use a
diferente lenguajes

stateless each pair of request and response comunicaction makes an independent transaccion.
continuar aun que ori servicio no funcione

The application is decomposed into microservices based on two categories.

Decompose by business capability

The services are created based on the business capabilities.

For example, in Retailer Ecommerce - billing, payment, order management, and


promotions are different business capabilities, which could be made into separate
services.

Decompose by subdomain

Domain-driven design supports modeling based on the reality of business as akin to use
cases.

Wrong decomposition could impact at the architectural level.

Application - Types

Applications are broadly classified into two types:

i) ***Monolithic Architecture***, where an application is built as a single unit.

ii) ***Microservices Architecture***, where many applications (microservices) handle a small


portion of the functionality and data.

We will discuss both these types in detail.


MONOLITIC STYLE

A monolithic application is built as a single unit, i.e., one big application in a single language that
handles all of the functionality, data, business logic etc.

A load balancer distributes requests from the end user, across multiple machines, each running
one instance of our application.

All logic for handling a request runs in a single process, allowing you to utilize the primary features
of the language to divide up

the application into classes, functions, and namespaces.

Advantages

Faster Initial Development - With one application, it would be relatively easy to add additional
features, especially when the application is relatively small.

Little User Confusion - Developers need not have to learn about different applications, but would
be focused towards one application.

Improved Integration - Features could integrate with each other well and easily.

Disadvantages
 Single Point of Failure - If any single
application function or component fails, then the entire application goes
down. For example - a web application with separate functions handling
tasks like payment, login, and history; a function begins to consume more
memory or CPU. In this scenario, the entire application will come to a halt.
 Horizontal Scaling - Scaling application can only be accomplished by
deploying the same EAR/WAR packages in more servers. Every single copy
of the application in different servers will use the same number of primary
resources, which is usually not an effective way to design.
 As application grows, the code base grows with it, which can
overload IDE every time it loads the application. This definitely reduces
developer productivity.
 Substantially less iteration - a small change made to any part of the
application, requires the entire monolith to be rebuilt and deployed.
 Maintenance costs will shoot up exponentially with site size.
 High set-up costs - In order to get each new volunteer up and running,
the larger the application, the more difficult this would be.
Microservice Style
Build applications as suites of services (Modular approach)

 Each microservice exposes a common API accessed through the network


(as opposed to inter-process communication or shared memory on the
same machine).
 API calls are stitched mostly on the server to produce a page, although few
of this work is executed by the client querying individual microservices.

Big enterprise players such as Amazon, Netflix, Uber, Yelp and eBay have
adopted Microservices. Services are

 Independently deployable
 Scalable

Each service offers a secure module boundary, allowing different services to be


written in different programming languages.

Advantages
 Improved fault isolation: Larger applications can remain largely unaffected
by the failure of a single module with microservice style adoption.
 Removes Dependency: Eliminates long-term commitment to any single
technology stack.
 Easy Understanding: With the split of functionality, it gives more room for
new developers to understand the functionality of a service and make
enhancements easily.
 Easy Deployment: Microservices-based applications are deployed inside
containers providing better management.

Disadvantages
 Complexity - Deploying microservices can be a little complex, requiring
coordination among multiple services, which may not be as straightforward
as deploying a monolith.
 Multiple DBs - Managing multiple databases and transaction management
could be painful.
 Testing - Testing could be little cumbersome, as each dependent service
needs to be confirmed before one can start testing.
 Coordination - Handling requests across multiple independent services
requires proper workflow management. There can be a scenario where one
of the services may not be responding or remote calls experiencing latency.
Service discovery

Ayuda a la comunicación ejemplo cuando ves los partidos y ayudan a la toma de decisiones para
saber que es lo que mas se vio teniendo un análisis historial de frecuencia sin hacer el código y
aprende de ellos

3C's of Microservices
The three golden rules of Microservices include:

 Componentize

Componentization of single application into multiple serviceable components is the


most important activity. Best would be to start by defining a RESTful API to access
this service, then plan and create an implementation using comfortable
development language and platform

 Collaborate

Communication among bigger teams becomes complex, which results in


numerous mistakes and curbing the speed of development.

Collaboration among teams focuses around API


contracts and Technology standardization.
 Connect

The final delivery of an application requires more than the development of


the constituent components.

These components must be connected, presentation layer and additional


services must be layered in, then the completed application must be
delivered to users. Given that microservices must communicate using APIs.

You will learn more about them in detail in the next few cards.

Microservice Architecture
Loosely coupled, small and focused, lenguaje neutral boundend context
Microservice vs SOA
Microservice evolution de service oriented arquetecture quita la configuration de mas, mayor
dlexibilidad , independiente es mejor

To quickly summarize, main difference between SOA and Microservices is

 Size (granularity)
 Scope.

Microservice could be considered as a subset of SOA.

Patterns of Microservice Architecture

Having studied at a high level about the Microservice architecture, let us discuss the
different patterns in detail!
API Proxy vs Gateway
Api proxy – more secure

Transport security

Monitoring –SLAs, performans

Access levels api proxy needs a proxy

API Gateway for Microservices


Microservices provide fine-grained APIs based on client needs. Each client needs
to interact with multiple services to collect relevant information. For example,
a payment client needs to fetch data from several services such as product,
customer, and billing.

API Gateway takes care of the external traffic of coordinating with


different services. The API Gateway encapsulates the internal system
architecture and provides an API that is tailored to each client.

The API Gateway is liable for Protocol translation, Composition, and Request
Routing.

API Gateway Benefits


 Insulates the clients (internal structure of the application) from

Application partitioning into Microservices Location determination of service


instances.

 Provides specific API to each client, reducing the number of round trips
between the client and application.
 Simplifies the client by transferring logic for calling various services from the
client to API gateway.

Netflix has created a cloud-based IT architecture


that helps developers to release huge numbers of
software changes daily. The Netflix architecture
includes an API Gateway that handles
approximately 2 billion API edge requests daily,
which are handled by about 600+ microservices.
Communication

In a monolithic application, components invoke each another through function calls. But in
a microservices-based application, it is distributed across multiple services. Each service
instance must interact with the other using an ***Inter-process communication
(IPC) mechanism***. The services can communicate within themselves, either
through Messaging or Remote Procedure Invocation.

Interaction Styles
There are several client service interaction styles classified along two dimensions.
 One-to-one or One-to-many -- One-to-one – Every client request is
processed by specifically one service instance. -- One-to-many – Each
request is processed by several service instances.

One-to-One Interaction Types


Request/response – A client sends a request to service and waits for a response.
The client expects the response to arrive in a timely fashion. Sometimes request
could even block while waiting.

Notification (one-way request) – A client transmits a request to a service,


however, a reply is not expected or sent.

Async/Request response – A client transmits a request to service, which


responds asynchronously. The client does not block while waiting and is designed
with the assumption that the response might not arrive for a while.

One-to-Many Interaction Types


Subscribe/publish – A client publishes a notification message that is used by zero
or multiple interested services.

Async/publish responses- A client then publishes a request message and waits


a certain amount of time for responses from related services.

 Synchronous or Asynchronous -- Synchronous – The client expects a


timely response from the service and might even block while it waits. --
Asynchronous – The client does not block while waiting for a response,
and the response is not necessarily sent immediately.

Inter-Process Communication
The RPC-based mechanisms attempt to make invoking a remote service look
same as calling a local service. And during failure, they are entirely different.

Messaging makes these differences very explicit, so developers are not lulled into
a false sense of security.
Service Registry
Ever wondered, how do clients of a service/router know about the available
instances of a service? The solution is Service Registry.

 Service Registry acts as a database of services, their instances,


and corresponding locations.
 Service instances are registered with the service registry on startup and
deregistered on shutdown.
 Clients of the service/router query the service registry to find the available
instances of a service.
 Some of the famous service registries include - Eureka, Apache
Zookeeper, Consul, etc.

Service Discovery
Service instances have dynamically assigned network locations. Service instances
change dynamically due to Auto-scaling, Failures and Upgrades.

The client needs Service Discovery Mechanism to over come this. There are two
types of Service Discovery:

 Client-side discovery
 Server-side discovery

Client-side Service Discovery


The clients take the onus and are responsible for determining the network
locations of available service instances by querying a service registry. This is
a straight forward approach.

The clients use intelligent application-specific load-balancing decisions


using hashing. But on the other hand, all service clients should have this client-
side service discovery logic for each programming language and framework.

Netflix OSS is a good example for this.


Server-side Service Discovery
The client makes a request via a load balancer. The load balancer queries the
service registry and routes each request to an available service instance.

AWS Elastic Load Balancer (ELB) is an example of a server-side discovery


router.

Main benefit

 Details of discovery are abstracted from the client, thus eliminating the need
to implement discovery logic for each programming language and
framework.

Circuit Breaker
It functions similar to the electrical circuit breaker.

When the number of consecutive request failures crosses a threshold,

 The circuit breaker trips for limited timeout period and all attempts to invoke
the remote service fail immediately.
 After the expiry of the timeout, the circuit breaker allows a limited number of
test requests to pass through.
 If the requests are successful, the circuit breaker continues normal
operation. If there is a failure, the timeout period starts again.
GIT

Let us understand few basic concepts behind packages and package


management.
To start with, developers create code to solve some specific problems. Often, this
code is reusable and can be shared to ease fellow developers' work.
So, for the greater good, developers make their code available to all.
The individual file of a reusable code is called a Module.

Packages

A Package is a directory which contains one or more modules along with a file
called package.json.

Note: The terms module and package are used interchangeably.

Package Manager
A Package Manager, as the name suggests, helps developers share packages,
install packages and manage version upgrades.

There are many package managers like Bower and npm that developers can use.

Why so many Package Managers?


Every package manager is built for a specific purpose. So developers need to
choose packages based on their need.
For example, Bower is built specifically for front-end libraries like jquery,
angular, bootstrap and so on. It works on the principle of minimal resource
load which is essential for your front-end to load quickly.
On the other hand, npm is mostly used for node.js packages and developer
tools like Grunt, Gulp, CoffeeScript and so on. npm aims for stability and hence
loads all nested dependencies of a package.
Getting Started with npm
npm , by default, comes with NodeJS.
Working with npm is simple. Type npm followed by the command.
To start with, find the version of npm by using the command "v" or "version".

Try it Out - npm help

Spring Boot - Introduction

Spring Boot allows you to create operating, production-grade, stand-alone Spring


based Applications with ease.

Spring Boot Framework

 is an opinionated framework.
 is based on convention over configuration.
 can build stand-alone applications.
 can create a production-ready package.
 has Embedded Tomcat server.
To summarize, Spring Boot Framework is a pre-configured, pre-sugared set of
technologies/framework to minimize boilerplateconfiguration offering the
quickest way to get a Spring web application ready and operational with minimal
configuration/coding out-of-the-box.

Building a Spring Boot App


Here are the steps to build a simple Spring boot application.
 Generate a quick Java project with Maven command.
 Update pom.xml with the Spring web and other Spring boot dependencies.
 Add SpringApplication.run() method to bootstrap Spring application.
 Do a Maven clean build using mvn clean package command.
 Execute command mvn spring-boot:run to run the application.

Microservices are built with REST APIs, and the significant reason is that they
help in building loosely coupled services.

Spring Boot provides the flexibility to create REST APIs quickly, which are exposed
as various services.

This simple block diagram depicts various services built using Spring Boot REST
APIs being consumed by the client.

Building a Rest Controller

@RestController
@RequestMapping("/test/")
public class HospitalController {
@Autowired
private HospitalService hospitalService;
@RequestMapping(value = "/hospitals/{id}", method = RequestMethod.GET)
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) thr
ows Exception {
Hospital hospital = this.hospitalService.getHospital(id);
return hospital;
}
@RequestMapping(value = "/hospitals", method = RequestMethod.GET)
public @ResponseBody List<Hospital> getAllHospitals() throws Exception {
return this.hospitalService.getAllHospitals();
}
}

Add a Data Transfer Object class


public class Hospital {
private int id;
private String name;
private String city;
private double rating;
public Hospital(int id, String name, String city, double rating)
{
this.id= id;
this.name= name;
this.city= city;
this.rating=rating;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}

Add a Service Class


@Service
public class HospitalService {
private List<Hospital> hospitalList=new ArrayList<>(Arrays.asList(
new Hospital(1001, "Apollo Hospital", "Chennai", 3
.8),
new Hospital(1002,"Global Hospital","Chennai", 3.5
),
new Hospital(1003,"VCare Hospital","Bangalore", 3)
));
public List<Hospital> getAllHospitals(){
return hospitalList;
}
public Hospital getHospital(int id){
return hospitalList.stream().filter(c->c.getId()==(id)).findFirst(
).get();
}
}
SQL Databases - Integration
Spring Boot Framework is quite flexible while working with SQL database. You
can use direct JDBC calls using JDBC templates, or you can go by
implementing hibernate.

One more significant option that Spring framework offers is by creating


repositories for Spring Data implementation.

Embedded Database
Spring Boot provides an option of an embedded in-memory database. This has
no persistent data storage. You can retain the data as long as the application is up
and running.
You can auto-configure Derby, HSQL and H2 databases by adding build
dependency to your pom.xml.

Embedded Database

Here is an example of configuring HSQL.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>

Spring Data JPA


What is JPA?
Java Persistence API is a specification that lets you do Object-Relational
Mapping (ORM) over a relational database.
What is ORM?
ORM allows you to map the entity classes to your relational SQL database.
What is Spring Data JPA?
Spring Framework handles ORM in an easy and quick fashion using JPA.

Customizing App with Spring Data JPA


Let's now add an embedded database and do a couple of database operations on
the same REST API project created earlier.
Step 1:
Add the following code to the pom.xml file to add an embedded database and JPA
dependencies.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

Spring Security
Spring Security can be broadly classified as

 Authentication
 Authorization

Spring Security architecture distinguishes both authentication and authorization.

Authentication

The interface defined for Authentication is Authentication Manager. This is a


single method Interface.

public interface AuthenticationManager {


Authentication authenticate(Authentication authentication)
throws AuthenticationException;

Securing Microservices
Below are the few techniques for securing Microservices.
 HTTP Basic - Client is authenticated with User Names and Password.

 X509 SSL Certificates - Authentication with a certificate for a secured


protocol.
 OAuth - This technique is used to authorize applications to access
information without giving them passwords.

HTTP Basic Authentication


HTTP Basic
 The client uses username and password as the authentication mechanism.
 User ID and password are sent to the service for authentication using
base64 encoded format.
 This is a sample template for authorization.
Authorization: Basic QWxhZGRghsgdhsVuIHNlc2FtZQ==

Basic Authentication
HTTP Digest technique is also similar to Basic Authentication.
 User ID and password are sent as a checksum of username and password.
 Both HTTP Basic and Digest technique are weak in terms of providing a
secured one.
 You need to use SSL/TLS encryption techniques to overcome the security
challenge.
 SSL/TLS encryption prevents man in the middle attacks.

OAuth 2.0
OAuth 2.0 is a protocol by which users will be allowed to access the resources
through third-party services exposed by Facebook, Google, Microsoft, etc.
OAuth 2.0 uses SSL to ensure that the data is highly secured.
These services expose partial data and keep the users' details protected.

Building a Basic Authentication


Let's add Basic Authentication to the Hospital List REST API.
Step: 1
You need to configure Security dependency in your pom.xml.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

Step 2:
Create a 'AuthenticationEntryPoint' class.

@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoi
nt {
@Override
public void commence(HttpServletRequest request, HttpServletResponse
response, AuthenticationException authEx)
throws IOException, ServletException {
response.addHeader("LoginUser", "Basic " +getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("springboot");
super.afterPropertiesSet();
}
}

Step 3:
Add a 'SpringSecurityConfig' config class to configure authorization.

@Configuration

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) thr
ows Exception {
auth.inMemoryAuthentication().withUser("username").passwor
d("password").roles("USER");
}
}

Integrating App with Spring Data JPA


Step 2:
Create an Entity class.

@Entity
public class Hospital {
@Id
private int id;
private String name;
private String city;
private double rating;
public Hospital() {}
public Hospital(int id, String name, String city, double rating)
{
this.id= id;
this.name= name;
this.city= city;
this.rating=rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}
public void setCity(String city) {
this.city = city;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}

Step 3:
Create a Repository class.

import org.springframework.data.repository.CrudRepository;
public interface HospitalRepository extends CrudRepository<Hospital,Integ
er>{
}

Step 4:
Modify Service class as below.

@Service
public class HospitalService {
@Autowired
private HospitalRepository hospitalRepository;
public List<Hospital> getAllHospitals(){
List<Hospital> hospitalList= new ArrayList<Hospital>();
hospitalRepository.findAll().forEach(hospitalList::add);
return hospitalList;
}
}

NoSQL Integration
Spring Boot uses Spring Data to integrate to various NoSQL technologies such as
MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire, Cassandra, Couchbase,
and LDAP.
Spring Boot autoconfiguration feature is available for integrating with the following
technologies.
LDAP, Couchbase, Cassandra, Redis, Solr, Elasticsearch, Neo4j, and MongoDB.
Source: https://docs.spring.io/
Spring Boot - Database Migration
Data Migration is defined as a process of carrying data between
environments/instances.
Two major tools that can be used for Database migration/versioning are
 Flyway
 Liquibase
The tools can be easily integrated with Spring Boot by adding maven plugin
to pom.xml.

Consuming REST Services


Spring provides RestTemplate framework to consume REST Services. This is
one of the easiest ways to consume REST services.
Below are the RestTemplate methods that can be used for various HTTP
methods.
GET

getForObject(java.lang.String, java.lang.Class<T>, java.lang.Object...)

getForEntity(java.lang.String, java.lang.Class<T>, java.lang.Object...)

POST

postForLocation(java.lang.String, java.lang.Object, java.lang.Object...)


postForObject(java.lang.String, java.lang.Object, java.lang.Class<T>, jav
a.lang.Object...)

Consuming REST Services


DELETE

delete(java.lang.String, java.lang.Object...)

HEAD

headForHeaders(java.lang.String, java.lang.Object...)

Any Request Type

exchange(java.lang.String, org.springframework.http.HttpMethod, org.sprin


gframework.http.HttpEntity<?>, java.lang.Class<T>, java.lang.Object...)

execute(java.lang.String, org.springframework.http.HttpMethod, org.spring


framework.web.client.RequestCallback, org.springframework.web.client.Resp
onseExtractor<T>, java.lang.Object...)

Building REST Service Consumer


Let's try to build a REST service client to consume a simple Google books API.
Step: 1
Let's add an additional dependency to the pom.xml that we used for building REST
services.
This is used for retrieving response entity as a JSON object.

<dependency>
<groupId>org.json</groupId>

<artifactId>json</artifactId>

</dependency>

Step 2:
Build a Consumer class.

@SpringBootApplication

public class RestBooksApi {

static RestTemplate restTemplate;

public RestBooksApi(){

restTemplate = new RestTemplate();

public static void main(String[] args) {

SpringApplication.run(SpringBoot4Application.class, args);

try {
JSONObject books=getEntity();

System.out.println(books);

catch(Exception e) {

e.printStackTrace();

/**

* get entity

* @throws JSONException

*/

public static JSONObject getEntity() throws Exception{

JSONObject books = new JSONObject();

String getUrl = "https://www.googleapis.com/books/v1/volum


es?q=isbn:0747532699";

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(headers
);

ResponseEntity<Map> bookList = restTemplate.exchange(getUr


l, HttpMethod.GET, entity, Map.class);

if (bookList.getStatusCode() == HttpStatus.OK) {

books = new JSONObject(bookList.getBody());

return books;

Spring Boot - Unit Testing


In your Spring Web MVC/RESt API, you will have to test all the three classes.
 Service class
 Repository class
 Controller class

Data Repository - Unit Testing


You need to add @DataJpaTestannotation with which you can
inject TestEntityManager bean.
Here is a sample class.
@RunWith(SpringRunner.class)

@DataJpaTest

public class HospitalRepositoryTest {

@Autowired

private TestEntityManager entityManager;

@Autowired

private HospitalRepository hospitalRepository;

@Test

public void testFindById() {

entityManager.persist(new Hospital(1003,"Vcare Hospital","Mumbai"


,3.1));

Hospital hosp = hospitalRepository.findOne(1003);

assertEquals("Vcare Hospital", hosp.getName());


}

MVC Controller - Unit Testing


Here is a unit testing class with MockMvc instance.

@SpringBootTest

@RunWith(SpringRunner.class)

public class HospitalControllerTest {

private MockMvc mockMvc;

@Autowired

WebApplicationContext context;

@Before

public void setup() {

mockMvc = MockMvcBuilders.webAppContextSetup(context).build();

}
@Test

public void retrievetest_ok() throws Exception {

mockMvc.perform(get("/test/hospitals/1000" )).andDo(print
())

.andExpect(status().isOk())

.andExpect(MockMvcResultMatchers.jsonPath("$.id").
value(1000))

.andExpect(MockMvcResultMatchers.jsonPath("$.name"
).value("Test Hospital"))

.andExpect(MockMvcResultMatchers.jsonPath("$.ratin
g").value(3.8))

.andExpect(MockMvcResultMatchers.jsonPath("$.city"
).value("Chennai"));

Unit Testing - Mock MVC 1


This image explains the unit testing workflow with mock MVC using Application
Context as a whole.

Unit Testing - Mock MVC - 2


In this method, unit testing is done using mock MVC over a stand-alone Controller.

Spring Boot - Integration Testing


You can do a quick Integration testing for your
application @SpringBootTest annotation. You can quickly configure a real
environment with the webEnvironment attribute added
to @SpringBootTest annotation.

This block diagram demonstrates integration testing from a web server using REST
Template.

TestRestTemplate gets auto-configured and injected into the test class.


Let's look into an example test class.

Integration Testing - Quick Example

@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment)

public class CreateClientIntegrationTest {

@Autowired

private TestRestTemplate restTemplate;

@Test

public void createClient() {

ResponseEntity<Client> responseEntity =

restTemplate.postForEntity("/test/hospitals", new Hospital(1,


"Test hospital","Chennai",3.9), Hospital.class);

Hospital hosp = responseEntity.getBody();

assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());

assertEquals("Test hospital", hosp.getName());


}

Spring Boot - Logging


By default, Spring Boot uses Logback to logging. Spring Boot starter spring-
boot-starter-logging should be configured to add logging dependencies.

Any starter added to the project comes with spring-boot-starter-


logging configured by default.
Any configuration on Logback logging has to be done
in application.properties or application.yml file.

Spring Boot - Logging


Let's see few configurations listed below.
 logging.level.: This is used to set the log level.

 logging.file: This is used to add a logging file name where you want your
logs to be added.
 logging.path: This property is used to configure the log file path. Spring
boot adds a default file spring.log
 logging.pattern.console: This property is used to define logging pattern
in the console.
 logging.pattern.file: This property is used to add logging pattern to a
file.
 logging.pattern.level: This property is used to define the format to
render log level. The default value is %5p.

Template Engines helps us to consume static templates in your application.

Below is the list of template engines that can be used with Spring Boot application.

 Thymeleaf
 Groovy
 FreeMarker

Template Engines - Thymeleaf


**Thymeleaf**is a template engine based on Java to process HTML and other file
types. This enables you to use the template as prototypes.
You need to add spring-boot-starter-thymeleaf starter to include this
template engine.
Here is the dependency to be added to your pom.xml file.

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

<version>1.5.6.RELEASE</version>

</dependency>

Template Engines - FreeMarker


FreeMarker is another template engine built in Java by Apache Software
Foundation.
Here is the dependency to be added to your pom.xml to include this template
engine.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>

You can use the **Groovy**template engine to generate Spring MVC views.
You need to add the below-mentioned dependency to your pom.xml to add this
template.

<dependency>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-groovy-templates</artifactId>

<version>1.5.6.RELEASE</version>

</dependency>

Spring Boot enables auto-configuration for Caching.

Let's consider this simple example.

import org.springframework.cache.annotation.Cacheable

import org.springframework.stereotype.Component;

@Component

public class RatingService {

@Cacheable("premium")

public int computePremium(int rate) {

// ...

}
}

premium is marked @Cacheable, which means that if the value of rate is going to
be the same, Spring Boot does not compute the premium value, rather fetch the
same from the cache.

Spring Boot - Supported Cache Providers


Here is the list of Cache providers supported by Spring Boot.
 Generic
 JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, etc.)
 EhCache 2.x
 Hazelcast
 Infinispan
 Couchbase
 Redis
 Caffeine
 Guava (deprecated)
 Simple
Source: https://docs.spring.io/

Messaging
Spring Framework offers JMSTemplate to async messaging with JMS API.

You can also auto-configure RabbitTemplate and RabbitMQ using Spring Boot
Auto Configuration feature.

Spring Boot also has features for STOMP messaging.

Bootstrap Your App

Spring Initializr

The Quickest and Easiest way to bootstrap your application is by using Spring
Initializr ***http://start.spring.io/***.

Using this tool, you can generate all types of Spring boot project with the flexibility
to choose the Spring Boot version that you would want to adopt.

Spring Initializr

Here is a quick demo to generate a Spring Boot project with the dependencies
configured within few seconds.

Spring UI Framework - Vaadin


Vaadin Framework
Vaadin is a Java-based UI Web framework. This framework works best
on Spring and Spring Boot projects.
Spring/Spring Boot features such as Dependency Injection and
typical Convention over Configuration features make this a well-suited
framework to set up a Vaadin project.
The significant feature of this framework is that all UI code is written in Java and
this is run on server side JVM, which is then rendered as HTML5.

Spring Batch

Spring Batch is a lightweight framework that can quickly run scheduled jobs.

This framework also provides additional features such as logging, transaction


management, job statistics, etc.

Spring Batch jobs can be easily scaled up by executing job steps in parallel as
well as multiple threads in parallel.

You might also like