0% found this document useful (0 votes)
35 views31 pages

10 Microservices

all about 10 Microservices

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views31 pages

10 Microservices

all about 10 Microservices

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MICRISERVICES

STUDY GUIDE

Module 1
Introduction to MicroServices

Author
Som Prakash Rai

www.jtcindia.org 1 Spring MicroServices


A. Monolithic Architecture :
 Monolithic Architecture is a traditional architecture for enterprise applications.
 Dependencies are managed by dividing the application into layers that
perform logical functions as follows

Presentation — responsible for handling HTTP requests and responding


with either HTML or JSON/XML (for web services APIs).

o Business logic — the application’s business logic.

o Database access — data access objects responsible for access the


database.

o Application integration — integration with other services (e.g. via


messaging or REST API).

 A layer can only call into layers that sit next to it. It can be hard to introduce
changes in one part of the application without touching the rest of the
application. That makes complex for frequent updates and limiting how
quickly new features can be added.

 A monolithic application has single code base with multiple modules.


Modules are divided as either for business features. It has single build system
which builds entire application. It also has single executable or deployable
binary.

a) Benefits of Monolithic Architecture:


 Simple to develop.
 Simple to test. For example you can implement end-to-end testing by simply
launching the application and testing the UI with Selenium.
 Simple to deploy. You just have to copy the packaged application to a server.
 Simple to scale horizontally by running multiple copies behind a load
balancer.

 In the early stages of the project it works well and basically most of the big
and successful applications which exist today were started as a monolith.

 Prefer for Traditional business domains which has low Frequency of updates

www.jtcindia.org 2 Spring MicroServices


b) Challenges with Monolithic Applications:
1) Large monolithic code base makes complicated to understand, especially for
new developer.

2) Overloaded IDE, Large code base makes IDE slow, build time increase.

3) Deployment challenges.
Any change in the any one module would require the entire application to be
deployed again.
Continuous deployment is difficult.
You must redeploy the entire application on each update.

4) Scaling become challenging.

5) Big database.
6) Fault Tolerance.
If a specific feature is not working it will make the system goes down. In
order to handle this problem, the system has to be rebuilt, retested and
redeployed

Bug in any module (e.g. memory leak) can potentially bring down the entire
process. Moreover, since all instances of the application are identical, that
bug will impact the availability of the entire application.

7) Monolithic applications have a problem to adopting new technologies. Since


changes in frameworks or languages will affect an entire application it is
extremely expensive in both time and cost.

8) Extremely difficult to change technology or language or framework (hybrid


technologies) because everything is tightly coupled and depend up on each
other.

 Application architecture has always been evolving alongside


demanding business requirements and the evolution of technologies.

www.jtcindia.org 3 Spring MicroServices


B. What are microservices?

1) Microservices are small, independent, and loosely coupled.

2) A single small team of developers can write and maintain a service.

3) Each service has a separate codebase, which can be managed by a small


development team.

4) Services can be deployed independently. A team can update an existing


service without rebuilding and redeploying the entire application.

5) Services are responsible for persisting their own data or external state. This
differs from the traditional model, where a separate data layer handles data
persistence.

6) Services communicate with each other by using well-defined APIs. Internal


implementation details of each service are hidden from other services.

7) Services don't need to share the same technology stack, libraries, or


frameworks.

8) Prefer for Complicated domain which has high Frequency of updates.

a) Microservices benefits

1) Supports polyglot architecture


Each Microservice can run with its own architecture or technology or
different versions of same technology.

2) Enabling experimentation and innovation


With large monolithic applications, experimentation was not easy. With
Microservices, it is possible to write a small microservice to achieve the
targeted functionality and plug it into the system.

3) Small, focused teams:


A microservice should be small enough that a Small team can build, test, and
deploy it. Small team sizes promote greater agility. Large teams tend be less
productive, because communication is slower, management overhead goes up,
and agility diminishes.

www.jtcindia.org 4 Spring MicroServices


4) Agility:
Because microservices are deployed independently, it's easier to manage bug
fixes and feature releases. You can update a service without redeploying the
entire application, and roll back an update if something goes wrong. In many
traditional applications, if a bug is found in one part of the application, it can
block the entire release process. New features may be held up waiting for a bug
fix to be integrated, tested, and published.

5) Small code base:


In a monolithic application, there is a tendency over time for code
dependencies. Adding a new feature requires touching code in a lot of places. By
not sharing code or data stores, a Microservices architecture minimizes
dependencies, and that makes it easier to add new features.

6) Selective scaling
A monolithic application, packaged as a single WAR or an EAR, can only be
scaled as a whole. In Microservices, each service could be independently scaled
up or down depending on scalability requirement. As scalability can be
selectively applied at each service, the cost of scaling is comparatively less with
the microservices approach.

7) Fault isolation:
If an individual microservice becomes unavailable, it won't disrupt the entire
application, as long as any upstream microservices are designed to handle faults
correctly.

8) Data isolation:
It is much easier to perform schema updates, because only a single
microservice is affected. In a monolithic application, schema updates can
become very challenging, because different parts of the application may all
touch the same data, making any alterations to the schema risky.

9) Allowing substitution
Microservices are self-contained, independent deployment modules enabling
the substitution of one microservice with another similar microservice. Many
large enterprises follow buy-versus-build policies to implement software
systems. A common scenario is to build most of the functions in house and buy
certain niche capabilities from specialists outside.

www.jtcindia.org 5 Spring MicroServices


10) Supporting Cloud
11) Enabling DevOps
Microservices are one of the key enablers of DevOps. DevOps is widely
adopted as a practice in many enterprises, primarily to increase the speed of
delivery and agility. DevOps advocates having agile development, high-velocity
release cycles, automatic testing, and automated deployment.

b) Challenges with MicroService Architecture


 The benefits of microservices don't come for free. Here are some of the
challenges to consider before embarking on a microservices architecture.

1) Complexity:
A microservices application has more moving parts than the equivalent
monolithic application. Each service is simpler, but the entire system as a
whole is more complex.

2) Development and testing:


Existing tools are not always designed to work with service dependencies.
Refactoring across service boundaries can be difficult. It is also
challenging to test service dependencies, especially when the application
is evolving quickly.

3) Lack of governance:
The decentralized approach to building microservices has advantages, but
it can also lead to problems. You may end up with so many different
languages and frameworks that the application becomes hard to maintain.
It may be useful to put some project-wide standards in place, without
overly restricting teams' flexibility. This especially applies to cross-cutting
functionality such as logging.

4) Network congestion and latency:


The use of many small, granular services can result in more interservice
communication. Also, if the chain of service dependencies gets too long
(service A calls B, which calls C...), the additional latency can become a
problem. You will need to design APIs carefully. Avoid overly chatty APIs,
think about serialization formats, and look for places to use asynchronous
communication patterns.

www.jtcindia.org 6 Spring MicroServices


5) Data integrity :
With each microservice responsible for its own data persistence. As a
result, data consistency can be a challenge. Embrace eventual consistency
where possible.

6) Management:
To be successful with microservices requires a mature DevOps culture.
Correlated logging across services can be challenging. Typically, logging
must correlate multiple service calls for a single user operation.

7) Skillset:
Microservices are highly distributed systems. Carefully evaluate whether
the team has the skills and experience to be successful.

c) Key Points about MicroService Architecture

1) In the microservices architecture, there is no more application development


rather service development.

2) Microservices expose service endpoints as APIs and abstract all their


realization details i.e., the internal implementation logic, architecture, and
technologies are completely hidden behind the service API.

3) Messaging (JMS / AMQP), HTTP, and REST are commonly used for
interaction means communication between microservices.

4) Microservices are reusable business services.

5) Well-designed microservices are stateless and does not share any


conversational state maintained by the services.

6) Microservices are discoverable.

d) Number Of Endpoints for a Microservice


 The number of endpoints is not really a decision point. In some cases, there
may be only one endpoint, whereas in some other cases, there can be more
than one endpoint in a microservice.

www.jtcindia.org 7 Spring MicroServices


e) Communication styles
 Communication between microservices can be happen in two ways.
o Synchronous Communication
o ASynchronous Communication

 SYNchronous Communication
o In synchronous communication, the http listener such as tomcat or
jetty or jboss, etc is needed but not messaging listener. When a caller
requests a service, it passes the required information and waits for a
response.

Advantages:
1) No messaging server overhead.
2) The error will be propagated back to the caller immediately.

Disadvantages:
1) The caller has to wait until the request has been processed.
2)Adds hard dependencies (tight coupling) between Microservices i.e., if
one service in the chain fails, then the entire service chain will fail.

 ASYNchronous Communication
o The asynchronous style is based on reactive event loop semantics
which decouple microservices.

Advantages:
1) Decouple Microservices
2) Higher level of scalability because services are independent. Hence if
there is a slowdown in one of the services, it will not impact the entire
chain.

Disadvantages:
1) It has a dependency to an external messaging listener.
2) It is complex to handle the fault tolerance of a messaging listener.

www.jtcindia.org 8 Spring MicroServices


f) Number Of VMs per MicroService
 The one microservice can be deployed in one or multiple Virtual Machines
(VMs) by replicating the deployment for scalability and availability.

 Multiple Microservices can be deployed in one VM if the service is simple and


the traffic volume is less.

 In case of cloud infrastructure, the developers need not to worry about


where the services are running. Developers may not even think about
capacity planning. Services will be deployed in a compute cloud. Based on the
infrastructure availability and the nature of the service, the infrastructure
self-manages deployments.

g) Can microservices share data stores?


 In principle, microservices should abstract presentation, business logic, and
data stores i.e., each microservice logically could use an independent
database.

 Shared data models, Shared schema, and shared tables are disasters when
developing microservices.

 If the services have only a few tables, it may not be worth investing a full
instance of a database like MySQL instance. In such cases, schema level
segregation is good enough to start with.

h) Shared Libraries
 Sometimes code and libraries may be duplicated in order to adhere to
autonomous and self-contained principle.

i) Microservices early adopters


Many organizations have already successfully embarked on their journey to the
microservices world.

1) Netflix
Netflix, an international on-demand media streaming company, is a pioneer
in the microservices space.
Netflix transformed their large pool of developers developing traditional
monolithic code to smaller development teams producing microservices. At
Netflix, engineers started with monolithic, went through the pain, and then
broke the application into smaller units that are loosely coupled and aligned to
the business capability.

www.jtcindia.org 9 Spring MicroServices


2) Amazon
The well-architected monolithic application was based on a tiered
architecture with many modular components. However, all these components
were tightly coupled. As a result, Amazon was not able to speed up their
development cycle. Amazon then separated out the code as independent
functional services, wrapped with web services, and eventually advanced to
microservices.

3) Twitter
When Twitter experienced growth in its user base, they went through an
architecture-refactoring cycle. With this refactoring, Twitter moved away from a
typical web application to an API-based event driven code. Twitter uses Scala
and Java to develop microservices with polyglot persistence.

4) Uber
When Uber expanded their business from one city to multiple cities, the
challenges started. Uber then moved to microservice based architecture by
breaking the system into smaller independent units. Each module was given to
different teams and empowered them to choose their language, framework, and
database. Uber has many microservices deployed in their ecosystem using REST.

5) eBay :
In 2011, when eBay was introducing microservices, the company had 97
million active users and 62 billion gross merchandise volume. On a typical day,
eBay IT systems had to deal with massive traffic, like 75 billion database calls, 4
billion page views and 250 billion search queries. The change to microservice
architecture wasn’t the first major switch of technology at eBay; the company
faced similar transitions in 1999 and 2005.

Microservices were not invented; rather they were evoluated


from the previous architecture styles .

www.jtcindia.org 10 Spring MicroServices


Building microservices with Spring Boot and Spring Cloud
 Traditionally a war was explicitly created and deployed on a Tomcat server.
But microservices need to develop services as executable s, self-contained
JAR files with an embedded HTTP listener (such as tomcat or jetty).

 Spring boot is a tool to develop such kinds of services i.e., Spring Boot
enables microservices development by packaging all the required runtime
dependencies in a executable fat jar file.

Software Required
1. JDK 1.8
2. Spring Tool Suite
3. Maven 3.x /Gradle
4. Spring Framework 5.x RELEASE
5. Spring Boot 2.x RELEASE
6. RabbitMQ / Kafka
7. Git
8. Spring Cloud
9. MySQL DB

What You will learn Now


1. Cloud Config Server
2. Cloud Config Client
3. Cloud Bus
4. Eureka
5. Zuul
6. Feign
7. Ribbon
8. Hysterix
9. Sleuth
10.RabbitMQ
More….

www.jtcindia.org 11 Spring MicroServices


JTCBookStore

Som
JTC
Prakash

Som
JTC
Prakash

Som
JTC
Prakash

JTCBookStore

SomPrakash

JTC

www.jtcindia.org 12 Spring MicroServices


JTCBookStore

Som
JTC
Prakash

Som
JTC
Prakash

JTCBookStore

www.jtcindia.org 13 Spring MicroServices


JTCBookStore

JTCBookStore

www.jtcindia.org 14 Spring MicroServices


JTCBookStore

www.jtcindia.org 15 Spring MicroServices


 Application Name : MyBookSearchMS

 Ports : 8000 , 8100 ,8200

Steps to Develop MyBookSearchMS :

A) Setup the Database:

1) Create and open the database

drop database jtcbooksdb;


create database jtcbooksdb;
use jtcbooksdb;

2) Create the tables required

drop table mybooks;

create table
mybooks( book_id int
primary key, book_name
char(30), author char(15),
publications char(15),
category char(15)
);

drop table mybookratings;

create table
mybookratings( book_id int
primary key, avg_rating double,
number_of_searches int
);

drop table mybookinventory;

create table
mybookinventory( book_id int
primary key, books_available int
);

www.jtcindia.org 30 Spring MicroServices


3) Insert some sample records

insert into mybooks values(101,'Master Spring


Boot','Somprakash','jtc','Spring'); insert into mybooks values(102,'Master
MicroServices','Som','jtc','Spring'); insert into mybooks values(103,'Master
Angular','Somprakash','jtc','Web'); insert into mybooks values(104,'Master
React','Som','jtc','Web');
insert into mybooks values(105,'Master Spring Framework','Somprakash','jtc','Spring');
insert into mybooks values(106,'Master Spring Security','Rai','jtc','Spring');
insert into mybooks values(107,'MasterVue JS','Somprakash','jtc','Web');
insert into mybooks values(108,'Node JS','Rai','jtc','Web');
insert into mybooks values(109,'Master Spring Rest','Somprakash','jtc','Spring');

insert into mybookratings values(101,3.5,99);


insert into mybookratings values(102,3.5,99);
insert into mybookratings values(103,3.5,99);
insert into mybookratings values(104,3.5,99);
insert into mybookratings values(105,3.5,99);
insert into mybookratings values(106,3.5,99);
insert into mybookratings values(107,3.5,99);
insert into mybookratings values(108,3.5,99);
insert into mybookratings values(109,3.5,99);

insert into mybookinventory values(101,50);


insert into mybookinventory values(102,50);
insert into mybookinventory values(103,50);
insert into mybookinventory values(104,50);
insert into mybookinventory values(105,50);
insert into mybookinventory values(106,50);
insert into mybookinventory values(107,50);
insert into mybookinventory values(108,50);
insert into mybookinventory values(109,50);

4) Select and see the sample records

select * from mybooks


select * from mybookratings;
select * from mybookinventory;

www.jtcindia.org 31 Spring MicroServices


B) Setup the Boot Project

5) Copy BookPriceMS and Paste as BookSearchMS

6) Remove All except the following

a) pom.xml
b) application.properties
c) jtcBookPriceConfig.java
d) BookPriceApplication.java

7) Update pom.xml

*** Change Names



<groupId>com.jtcindia.booksearch</groupId>
<artifactId>BookSearchMS</artifactId>
….
<name>MyBookSearchMS</name>
….
<finalName>MyBookSearchMS</finalName>

8) Update application.properties

spring.application.name=MyBookSearchMS
server.port=8000
spring.datasource.url=jdbc:mysql://localhost:3306/jtcbooksdb

9) Rename the Package to com.jtcindia.booksearch

10) Rename Spring Bean Configuration Class


*** jtcBookSearchConfig.java

11) Rename BootApplication Starting Class.


*** BookSearchApplication.java

C) Develop the BookSearch MicroService Code:

12) Write the JPA Entities

*** Book.java
*** BookRating.java
*** BookInventory.java

www.jtcindia.org 32 Spring MicroServices


13) Write DAO Layer components
*** BookDAO.java
*** BookRatingDAO.java
*** BookInventoryDAO.java

14) Write DTO


*** BookPriceInfo.java
*** BookInfo.java

15) Write Service Layer components


*** BookService.java
*** BookServiceImpl.java

16) Write Controller Layer component


*** BookController.java

17) Start the Boot Application

18) Open the Swagger UI :

http://localhost:8000/swagger-ui.html

GET :
http://localhost:8000/mybooks/Somprakash/Spring
GET : http://localhost:8000/mybook/101

PUT : http://localhost:8000/updateBookRating
PUT : http://localhost:8000/updateBookInventory

19) Test with Browser

http://localhost:8000/mybooks/Somprakash/Web
http://localhost:8000/mybooks/Somprakash/Spring

http://localhost:8000/mybook/101
http://localhost:8000/mybook/102

www.jtcindia.org 33 Spring MicroServices


1. BookController.java 2. BookPriceInfo.java
3. BookInfo.java 4. BookService.java
5. BookServiceImpl.java 6. BookDAO.java
7. BookRatingDAO.java 8. BookInventoryDAO.java
9. Book.java 10. BookRating.java
11. BookInventory.java 12. jtcBookSearchConfig.java
13. StartMyBookSearchMS.java 14. application.properties
15. pom.xml

1. BookController.java
package com.jtcindia.booksearch;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.ApiOperation;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@CrossOrigin
@RestController
public class BookController {

static Logger log = LoggerFactory.getLogger(BookController.class);

@Autowired
BookService bookService;

@GetMapping("/mybooks/{author}/{category}")
@ApiOperation(value = " getBooks", response = List.class, notes = "Returns List of
Books for given Author and Category")
public List<Book> getBooks(@PathVariable String author, @PathVariable String category)
{ log.info("---BookController---getBooks()----");
System.out.println(author + "\t" + category);

return bookService.getBooks(author, category);


}

www.jtcindia.org 34 Spring MicroServices


@GetMapping("/mybook/{bookId}")
@ApiOperation(value = " getBookById", response = BookInfo.class, notes = "Returns
BookInfo for given BID")
public BookInfo getBookById(@PathVariable Integer bookId)
{ log.info("---BookController---getBookById()----");

return bookService.getBookInfo(bookId);
}

@PutMapping("/updateBookRating")
@ApiOperation(value = " updateBookRating", response = void.class, notes =
"updateBookRating")
public void updateBookRating(@RequestBody BookRating bookRating)
{ System.out.println("-------BookController-----updateBookRating()---- ");

bookService.updateBookRating(bookRating);
}

@PutMapping("/updateBookInventory")
@ApiOperation(value = " updateBookInventory", response = void.class, notes =
"updateBookInventory")
public void updateBookInventory(@RequestBody BookInventory bookInventory)
{ System.out.println("-------BookController-----updateBookInventory()---- ");

bookService.updateBookInventory(bookInventory);
}
}

2. BookPriceInfo.java
package com.jtcindia.booksearch;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
public class BookPriceInfo
{ private Integer bookId;
private double price;
private double offer;

//Constructors
//Setters and Getters
//toString()
}

www.jtcindia.org 35 Spring MicroServices


3. BookInfo.java
package com.jtcindia.booksearch;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
public class BookInfo {
private Integer bookId;
private String bookName;
private String author;
private String publications;
private String category;

private double price;


private double offer;

private double avgRating;


private int numberOfSearches;

private int booksAvailable;

//Constructors
//Setters and Getters
//toString()
}

4. BookService.java
package com.jtcindia.booksearch;

import java.util.List;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
public interface BookService {
public List<Book> getBooks(String author,String category);
public BookInfo getBookInfo(Integer bookId);
public void updateBookRating(BookRating bookRating);
public void updateBookInventory(BookInventory bookInventory);
}

www.jtcindia.org 36 Spring MicroServices


5. BookServiceImpl.java
package com.jtcindia.booksearch;

import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@Service
@Transactional
public class BookServiceImpl implements BookService{

static Logger log=LoggerFactory.getLogger(BookServiceImpl.class);

@Autowired
BookInventoryDAO bookInventoryDAO;

@Autowired
BookRatingDAO bookRatingDAO;

@Autowired
BookDAO bookDAO;

@Override
public List<Book> getBooks(String author, String category)
{ List<Book> mybooks=new ArrayList<>();

if(author.equals("All Authors") && category.equals("All Categories"))


{ mybooks = bookDAO.findAll();
}else if(author.equals("All Authors") && ! category.equals("All Categories"))
{ mybooks = bookDAO.getBooksByCategory(category);
} else if( ! author.equals("All Authors") && category.equals("All Categories"))
{ mybooks = bookDAO.getBooksByAuthor(author);
}else {
mybooks = bookDAO.getBooksByAuthorAndCategory(author, category);
}
return mybooks;
}

www.jtcindia.org 37 Spring MicroServices


public BookInfo getBookInfo(Integer bookId)

{ BookInfo bookInfo=new BookInfo();

//1. Book Details


Book book=bookDAO.findById(bookId).get();
bookInfo.setBookId(book.getBookId()); //1
bookInfo.setBookName(book.getBookName());//2
bookInfo.setAuthor(book.getAuthor()); //3
bookInfo.setPublications(book.getPublications());//4
bookInfo.setCategory(book.getCategory());//5

//2. Book Rating Details


BookRating bookRating=bookRatingDAO.findById(bookId).get();

bookInfo.setAvgRating(bookRating.getAvgRating());//6
bookInfo.setNumberOfSearches(bookRating.getNumberOfSearches());//7

//3. Book Inventory Details


BookInventory bookInventory=bookInventoryDAO.findById(bookId).get();
bookInfo.setBooksAvailable(bookInventory.getBooksAvailable());//8

//4.Book Price Details – Invoking BookPriceMS


RestTemplate bookPriceRest=new RestTemplate();
String endpoint="http://localhost:9000/bookPrice/"+bookId;
BookPriceInfo bpInfo=bookPriceRest.getForObject(endpoint, BookPriceInfo.class);
bookInfo.setPrice(bpInfo.getPrice());//9
bookInfo.setOffer(bpInfo.getOffer());//10

return bookInfo;
}

@Override
public void updateBookRating(BookRating bookRating)
{ bookRatingDAO.save(bookRating);
}

@Override
public void updateBookInventory(BookInventory bookInventory)
{ bookInventoryDAO.save(bookInventory);
}
}

www.jtcindia.org 38 Spring MicroServices


6. BookDAO.java
package com.jtcindia.booksearch;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@Repository
public interface BookDAO extends JpaRepository<Book,Integer> {
public List<Book> getBooksByAuthorAndCategory(String author,String category);
public List<Book> getBooksByAuthor(String author);
public List<Book> getBooksByCategory(String category);
}

7. BookRatingDAO.java
package com.jtcindia.booksearch;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@Repository
public interface BookRatingDAO extends JpaRepository<BookRating,Integer> {
}

8. BookInventoryDAO.java
package com.jtcindia.booksearch;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@Repository
public interface BookInventoryDAO extends JpaRepository<BookInventory,Integer> {
}

www.jtcindia.org 39 Spring MicroServices


9. Book.java
package com.jtcindia.booksearch;

import javax.persistence.*;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */

@Entity
@Table(name="mybooks",schema = "jtcbooksdb")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="book_id")
private Integer bookId;

@Column(name="book_name")
private String bookName;

@Column(name="author")
private String author;

@Column(name="publications")
private String publications;

@Column(name="category")
private String category;

//Constructors
//Setters and Getters
//toString()
}

10. BookRating.java
package com.jtcindia.booksearch;

import javax.persistence.*;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */

www.jtcindia.org 40 Spring MicroServices


@Entity
@Table(name="mybookratings",schema = "jtcbooksdb")
public class BookRating {

@Id
@Column(name="book_id")
private Integer bookId;

@Column(name="avg_rating")
private double avgRating;

@Column(name="number_of_searches")
private int numberOfSearches;

//Constructors
//Setters and Getters
}

11. BookInventory.java
package com.jtcindia.booksearch;

import javax.persistence.*;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */

@Entity
@Table(name="mybookinventory",schema = "jtcbooksdb")
public class BookInventory {
@Id
@Column(name="book_id")
private Integer bookId;

@Column(name="books_available")
private int booksAvailable;

//Constructors
//Setters and Getters
}

www.jtcindia.org 41 Spring MicroServices


12.jtcBookSearchConfig.java
package com.jtcindia.booksearch;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.google.common.base.Predicates;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@SpringBootApplication
public class jtcBookSearchConfig implements WebMvcConfigurer {

private ApiInfo getApiDetails() {


return new ApiInfo("jtc BookStore- API",
"BookSearchMS- API - part of BookStore", "1.0", "Free to use ",
new Contact("Somprakash Rai", "https://www.jtcindia.com", "[email protected]"),
"API Under Free Licence", "https://www.jtcindia.com");
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select().paths(PathSelectors.any())
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))).b
uild().apiInfo(getApiDetails());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-
INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-
INF/resources/webjars/");
}
}

www.jtcindia.org 42 Spring MicroServices


13. BookSearchApplication.java
package com.jtcindia.booksearch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import springfox.documentation.swagger2.annotations.EnableSwagger2;
/*
* @Author : Somprakash Rai
* @company : JtcIndia
* */
@SpringBootApplication
@EnableSwagger2
public class BookSearchApplication {
static Logger log = LoggerFactory.getLogger(BookSearchApplication.class);

public static void main(String args[])


{ log.info(" BookSearchMS - Begin ");
SpringApplication.run(BookSearchApplication.class, args);
log.info(" BookSearchMS - End ");
}
}
14. application.properties
spring.application.name=MyBookSearchMS

server.port=8000

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jtcbooksdb
spring.datasource.username=root
spring.datasource.password=Somprakash

spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} - %msg%n

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

www.jtcindia.org 43 Spring MicroServices


15. pom.xml
<project …>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.booksearch</groupId>
<artifactId>BookSearchMS</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>MyBookSearchMS</name>
<url>https://www.jtcindia.com</url>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

www.jtcindia.org 44 Spring MicroServices


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

</dependencies>

<build>
<finalName>MyBookSearchMS</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

MicroService Name Rest Endpoints


MyBookSearchMS http://localhost:8000/mybooks/{author}/{category}

MyBookSearchMS http://localhost:8000/mybook/{bookId}

MyBookSearchMS http://localhost:8000/updateBookRating

MyBookSearchMS http://localhost:8000/updateBookInventory

www.jtcindia.org 45 Spring MicroServices

You might also like