Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
87 views33 pages

Microservices Notes

The document compares Monolith and Microservices architectures, outlining their advantages and disadvantages. It details the implementation of Microservices using Spring Boot, including the setup of service registries, admin servers, and API gateways, as well as the integration of Redis for caching. Additionally, it covers Spring Boot Actuators for application monitoring and management, and discusses the use of application properties in .properties and .yml formats.
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)
87 views33 pages

Microservices Notes

The document compares Monolith and Microservices architectures, outlining their advantages and disadvantages. It details the implementation of Microservices using Spring Boot, including the setup of service registries, admin servers, and API gateways, as well as the integration of Redis for caching. Additionally, it covers Spring Boot Actuators for application monitoring and management, and discusses the use of application properties in .properties and .yml formats.
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
You are on page 1/ 33

Monolith Vs Microservices

Application can be developed in 2 ways


a. Monolith Architecture
b. Microservices Architecture
If we develop all the functionalities in one single application then it is called a Monolith Application.

Advantages
Development is easy
2) Deployment is easy
Performance
4) Easy Testing
5) Easy Debugging
6) KT is easy

Disadvantages
Single point of failure
2) Whole Application Re-Deployment
3) Scalability (Increasing & Decreasing resources based on demand)
4) Reliability (Strong)
5) Availability (Zero Downtime)
If we develop the functionalities in multiple services/apis then it is called Microservices Architecture.
Based Application.
Every Microservice will have its own goal

Advantages
Loosely coupled
Fast Development
Quick Releases
4) Flexibility
5) Scalability
6) No Single Point of failure
Technology independence
Challenges
1) Bounded context (identifying the number of services to develop)
A lot of configurations
3) Visibility
Testing is difficult
5) Debugging

Microservices Architecture
Microservices is an architectural design pattern to develop our applications.
There is no fixed architecture for Microservices Based Applications
People are customizing Microservices Architecture according to their requirement.

Let us see the generalized architecture of Microservices


Service Registry
2) Admin Server
3) Zipkin Server
4) Services (REST APIs)
FeignClient
6) API Gateway
7) ServiceRegistry is used to register all our backend services/apis
8) Service Registry will maintain services names, urls and status of each service
9) We can use EurekaServer as a service registry
10) Note: EurekaServer provided by Spring Cloud Netflix Library
11) AdminServer is used to monitor and manage all our backend services in one place.
AdminServer will provide a user interface to monitor and manage our services.
Using the AdminServer user interface, we can access the Actuator Endpoints of our services in one place.
14) Note: AdminServer and Admin Client provided by 'Code Centric' company (we can integrate with
boot
15) ZipkinServer is used for Distributed Log Tracing
16) ZipkinServer will provide a user interface to monitor application execution details.
17) How many services were involved and which service took more time to process the request can be
monitored using Zipkin
18) Note: Zipkin is a third-party open source server (can be integrated with Spring Boot)
Backend services are nothing but REST APIs (which are also called as Microservices)
20) Backend REST APIs contain the actual business logic of our application
One project will have multiple REST APIs in the backend.
22) Each Backend API will act as a client for Service Registry + Admin Server + Zipkin Server
23) Within the same application, if one backend API is communicating with another backend API, then
it is called as Interservice communication
FeignClient will be used to perform Interservice Communication
25) Note: Based on requirement our backend APIs can communicate with 3rd party APIs using
RestTemplate or WebClient
26) The API Gateway will act as an entry point for our backend APIs.
It acts as a mediator between end users and backend APIs.
28) API Gateway contains Filters and Routing
29) Filters we can use to authenticate incoming requests
Routing will decide which request should go to which backend API.
31) Note: In previous versions we have Zuul Proxy as API Gateway but now it got removed from latest
version of boot
32) We can use Spring Cloud Gateway as an API Gateway for our application.

Microservices Mini Project Implementation


Step 1) Create Service Registry Application using Eureka Server
Create Spring Boot app with below dependencies
Spring-cloud-starter-netflix-eureka-server
b) web starter
c) devtools
2) Configure the @EnableEurekaServer annotation in the boot start class

3) Configure below properties in application.yml file


server
port: 8761
eureka
client
register-with-eureka: false
4) Run the application and access it in the browser

http://localhost:8761/
Step-2 ) Create Spring Boot Application with Admin Server
1) Create Boot application with the following dependencies

a) web-starter
b) devtools
c) admin-server (code centric)
2) Configure the @EnableAdminServer annotation in the boot start class

3) Configure Embedded Container Port Number (we can use any port)
4) Execute the application and access it in the browser.

http://localhost:port/
Step-3) Download & Run Zipkin Server
1) Download the zipkin jar from the below URL

https://search.maven.org/remote_content?g=io.zipkin&a=zipkin-server&v=LATEST&c=exec
2) Run the zipkin server jar file using the command below

$ java -jar <zipkin-server-jar>


Step-4) Develop REST API (WELCOME API)
1) Create a boot application with the following dependencies

eureka-discovery-client
b) admin-client
c) zipkin client
d) sleuth (It is for logging)
web-starter
f) devtools
g) actuator
2) Configure the @EnableDiscoveryClient annotation in the startup class (It will search and register with Eureka)

3) Create Rest Controller with required methods


4) Configure below properties in application.yml
a. server port
b. admin server url
c. actuator endpoints
d. application name
server:
8081
spring
application:
WELCOME-API
boot:
admin:
client
http://localhost:1111/
eureka
client
service-url
http://localhost:8761/eureka/
management
endpoints
web
exposure
include: '*'
5) Run the application and check the Eureka Dashboard, Admin Server Dashboard, and Zipkin Dashboard

Step-5) Develop REST API (GREET API)


1) Create a boot application with the following dependencies

eureka-discovery-client
(2) admin-client
(3) zipkin client
(4) sleuth (It is for logging)
(5) web-starter
devtools
actuator
feign-client
2) Configure @EnableDiscoveryClient & @EnableFeignClients annotations at the start class
3) Create FeginClient to access WELCOME-API
@FeignClient(name = "WELCOME-API")
public interface WelcomeApiClient {
/welcome
public String invokeWelcomeApi();
}
4) Create Rest Controller with required methods
5) Configure below properties in application.yml
server port
admin server url
actuator endpoints
application name
server
9091
spring
application
GREET-API
boot:
admin
client
http://localhost:1111/
Eureka:
client
service-url
http://localhost:8761/eureka/
management
endpoints
web
exposure
*
6) Run the application and check the Eureka Dashboard, Admin Server Dashboard, and Zipkin Dashboard
Step-6 :: Develop API-Gateway Application
1) Create boot application with the below dependencies

cloud-gateway
eureka-client
web-starter
devtools
Configure @EnableDiscoveryClient annotation at the boot start class
3) Configure Server Port & API Routings in application.yml file
server
port: 3333
spring
application
API-GATEWAY
cloud
gateway
discovery:
locator
enabled: true
true
routes
one
uri: lb://WELCOME-API
predicates:
/welcome
two
lb://GREET-API
predicates
/greet
4) Run the application and test it.
We can access Client sent request information using Filter
The client request information we can use to validate that request
Create the filter below in API Gateway (It will execute for every request)

@Component
public class MyPreFilter implements GlobalFilter {
Logger logger = LoggerFactory.getLogger(MyPreFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
filter() method executed....
Access request information
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
Set<String> keySet = headers.keySet();
keySet.forEach(key -> {
List<String> values = headers.get(key);
System.out.println(key + "::" + values);
});
return chain.filter(exchange);
}
}
When we send a request to the REST API using POSTMAN, it will send a POSTMAN Token in the request header.
Using this token we can differentiate requests that come from other apps or from POSTMAN.

Load Balancing

If we run our application on a Single Server then all requests will be sent to a single server.
Burden will be increased on the server
When the burden increases, request processing gets delayed.
Sometimes our server might crash due to heavy load
To overcome the above problems, we will use the Load Balancing concept.

Load Balancing is the process of distributing load to multiple servers


LBR implementation in Mini Project
Make the following changes in WelcomeApi Rest Controller

@RestController
public class WelcomeRestController {
@Autowired
private Environment env;
@GetMapping("/welcome")
public String welcomeMsg() {
String port = env.getProperty("server.port");
Welcome to Ashok IT..!! (Port ::
return msg;
}
}
Run Welcome API with 3 instances
Right Click on API
-> Run As -> Run Configurations
Select Application
-> Arguments
-> VM Arguments (-Dserver.port=8082)
Apply & Run it
Check Eureka Dashboard
What is Cache?
1) Cache is a temporary storage
When our application wants to access the same data frequently, then we will use cache memory.
Cache will improve the performance of our application by reducing database calls.
4) Note: Database calls are always costly which will take more time to execute.
5) To reduce the number of round trips between the application and the database, we will use 'Cache'.

Redis Cache
Redis is one of the distributed caches available in the market.
Redis will store data in key-value pair
Multiple Applications can connect with Redis Cache at a time...
The open source, in-memory data store used by millions of developers as a database, cache, streaming
engine, and message broker.

Redis Setup
1) Download Redis Software
2) URLhttps://redis.io/download/#redis-downloads
3) Run 'redis-server.exe' file
4) Note: By default it runs on '6379' port number
5) Run 'Redis-cli.exe' file
6) Type 'ping' command in Redis CLI
7) Note: The server will respond with 'PONG' as a response.

SPRING BOOT WITH REDIS INTEGRATION


Spring Boot provided starter pom to connect with Redis Server
2) Create JedisConnectionFactory bean
3) Create RedisTemplate and inject JedisConnectionFactory into RedisTemplate
4) Using RedisTemplate to get HashOperations object
5) Using HashOperations we can perform storing/retrieving/deleting operations with Redis Server

<dependency>
org.springframework.boot
spring-boot-starter-data-redis
<exclusions>
io.lettuce
lettuce-core

</dependency>
<dependency>
redis.clients
jedis
</dependency>

Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory getJedisConnection() {
JedisConnectionFactory factory = new JedisConnectionFactory();
// factory.setHostName(hostName);
// factory.setPassword(password);
// factory.setPort(port);
return factory;
}
Bean
@Primary
public RedisTemplate<String, User> getRedisTemplate(JedisConnectionFactory factory) {
RedisTemplate<String, User> rt = new RedisTemplate<>();
rt.setConnectionFactory(factory);
return rt;
}
}
package in.ashokit.binding;
import java.io.Serializable;
import lombok.Data;
@Data
public class User implements Serializable{
private Integer uid;
private String name;
private Integer age;
}

RestController
public class UserRestController {
private HashOperations<String, Integer, User> hashOps;
public UserRestController(RedisTemplate<String, User> redisTemplate) {
hashOps = redisTemplate.opsForHash();
}
/user
public String storeData(@RequestBody User user) {
hashOps.put("PERSONS", user.getUid(), user);
return "success";
}
@GetMapping("/user/{uid}")
public User getData(@PathVariable Integer uid) {
User value = (User) hashOps.get("PERSONS", uid);
return value;
}
@GetMapping("/users")
public List<User> getAllUsers() {
return hashOps.values("PERSONS");
}
@DeleteMapping("/user/{uid}")
public String deleteUser(@PathVariable Integer uid) {
hashOps.delete("PERSONS", uid);
User Deleted
}
}

Spring Boot Actuators


1) Actuator is one of the powerful features introduced in Spring Boot.
Actuators are used to monitor and manage our application.
3) Actuators are providing production-ready features for our boot application.

Actuator Endpoints

/health : To get application health status


2) /info : To get application information
3) /beans : To get what beans loaded by our application
4) /mappings: To get what URL patterns are available in our application
/configProps : To get configuration properties loaded by our application
6) /heapdump: To download heap data
7) /threaddump: To get threads information
/shutdown : To stop our application (This is special, it is bound to a POST request)

To work with actuators we have to use 'spring-boot-starter-actuator' dependency


<dependency>
org.springframework.boot
spring-boot-starter-actuator

We can see actuator exposed endpoints using the below URL

URL : http://localhost:8080/actuator
Note: /health is a default endpoint which we can access directly
We can expose other actuator endpoints using the below property.
application.yml
management
endpoints
web
exposure
*
Note: To expose endpoints using application.properties we will use the below property

management.endpoints.web.exposure.include=*

Working with shutdown


IT is used to stop our application
We need to enable this manually
It is bound to HTTP POST request

management
endpoints
web
exposure
*
endpoint:
shutdown
enabled: true

application.properties file vs application.yml file


1) When we create a Spring Boot application, the application.properties file will be created by default.

We can avoid hard coded values by configuring app properties in this application.properties file
3) properties file will represent data only in key-value format
i. Ex:
ii. server.port = 9090
/views/
.jsp
4) properties file will represent data in sequential format
5) properties file will be supported by only java
For every profile we need to create a separate properties file

As an alternate to .properties file we can use .yml file in spring boot


YML stands for YET ANOTHER MARKUP Language
YML represents data in hierarchical format
i. server:
ii. port: 9090
YML supports key-value, list, and map values also
YML is supported by other programming languages as well (It is universal)
5) All the profiles can be configured in a single YML file

Working with Dynamic Properties


application.yml
server
port: 9090
spring
application
sb-rest-api
messages
Welcome to Ashok IT..!!
Good Morning

@RestController
public class WelcomeRestController {
messages.welcome
private String welcomeMsg;
messages.greet
private String greetMsg;
@GetMapping("/welcome")
public String welcomeMsg() {
return welcomeMsg;
}
GetMapping("/greet")
public String greetMsg() {
return greetMsg;
}
}

Application messages and REST endpoint URLs are not recommended to be hardcoded in Java classes.
Because if we change any message or any URL then we have to compile and package the entire application.
To avoid this problem we will configure messages and URLs in the application.properties file or in
application.yml file
When we change the application.properties file or application.yml file, we do not need to compile and build.

entire project.

Working with App Properties


application.yml
spring
application
sb-yml-app
ashokit
messages
Welcome To Ashok IT
Good Morning
All the best
AppProperties.java
@Data
Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix="ashokit")
public class AppProperties {
private Map<String, String> messages = new HashMap<>();
}
DemoRestController.java
@RestController
public class DemoRestController {
@Autowired
private AppProperties props;
@GetMapping("/welcome")
public String getWelcomeMsg() {
Map<String, String> messages = props.getMessages();
messages.get("welcomeMsg");
return value;
}
@GetMapping("/greet")
public String getGreetMsg() {
Map<String, String> messages = props.getMessages();
System.out.println(messages);
messages.get("greetMsg");
return value;
}
@GetMapping("/wish")
public String getWishMsg() {
return props.getMessages().get("wishMsg");
}
}
Config Server
1) As part of our application development we will use several configuration properties
a. Ex:
a) data source properties
b) actuator properties
c) security properties
d) smtp properties
e) kafka properties
f) application messages etc..
As of now we configured those configuration properties in application.properties / application.yml file
The application.properties / application.yml file will be available within the project.
4) When we package our boot application for deployment, our configuration properties will be part of that.
packaged file
Note: If we want to change any configuration properties then we have to package our application again.
and we have to re-deploy our application (This is not recommended).
To avoid this problem we will keep configuration properties outside of the project.

Config server is used to externalize application configuration properties.


Using Config Server we can load Configuration Properties from outside of the project
2) When we want to change any configuration properties we do not need to re-package and re-deploy our
application
3) Using Config Server we can decouple our application and configuration properties

1) Create a GitHub repository and keep configuration properties in the GitHub repo
Note: We need to use the application name for configuration properties/yml file name

Ex:
Welcome
welcome-dev.yml
welcome-prod.yml
admin.yml
admin-dev.yml
admin-prod.yml
reports.yml
reports-dev.yml
reports-prod.yml

https://github.com/ashokitschool/configuration_properties.git

Config Server Project


1) Create Boot application with the following dependencies

a) config-server
b) actuator
2) Write @EnableConfigServer annotation at boot start class
3) Configure below properties in application.yml file
spring
cloud
config
server
git:
https://github.com/ashokitschool/configuration_properties
clone-on-start: true
management
security
enabled: false

Microservice To Load Config Properties using Config Server (Config Client App)
1) Create Boot application with the below dependencies

a) config-client
b) web-starter
cloud-bootstrap
2) Configure application name, application port, config-server-url, profile
app-name
spring
application
welcome
cloud
config
http://localhost:8080
b) application.yml (server port)
server
port: 9090
3) Create Rest Controller with required methods
@RestController
@RefreshScope
public class WelcomeRestController {
Config Server Not Working
private String msg;
@GetMapping("/")
public String getWelcomeMsg() {
return msg;
}
}
Run the application and test it.

Exception Handling In REST API


1) Exception is an unexpected and unwanted situation occurring in the application.
When an exception occurs, our program will terminate abnormally.
3) To achieve graceful termination of the program we need to handle the exception.
4) In Java we have the following keywords to handle exceptions

try: It is used to keep risky code


2) catch : Catch block is used to handle the exception
throw: It is used to re-throw the exception
4) throws : It is used to ignore the exception
5) finally: It is used to execute clean up logic (closing files, closing connection, release resources....)
Note: When we encounter an exception in the REST API, we should convey that exception information to the client.
application in json format
Ex:
{
Exception Reason
SBI0004
}
Note: In the project, for every exception we will use one CODE i.e. exception code.

In Spring web mvc we can handle exceptions in 2 ways.


1) Controller Based Exception Handling
Exception Handlers applicable for only particular controller
2) Global Exception Handling
Exception Handlers applicable for all the classes in the project
@Data
public class ExceptionInfo {

private String msg;


private String code;

}
@RestController
public class DemoRestController {
private Logger logger = LoggerFactory.getLogger(DemoRestController.class);
@GetMapping("/")
public String doAction() {
Action in progress
try {
Division by zero!
} catch (Exception e) {
logger.error("Exception Occurred ::" + e, e);
throw new ArithmeticException(e.getMessage());
}
return msg;
}
@ExceptionHandler(value=ArithmeticException.class)
public ResponseEntity<ExceptionInfo> handleAE(ArithmeticException ae) {
ExceptionInfo exception = new ExceptionInfo();
exception.setMsg(ae.getMessage());
AIT0004
return new ResponseEntity<>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Spring Security
1) To implement security for our applications, Spring provided the 'security' module.
To use Spring Security in our project 'spring-security-starter' we need to add in pom.xml file
<dependency>
org.springframework.boot
spring-boot-starter-security

By default it will secure all the endpoints of our application.


Default username: user
Default Pwd: Will be printed on the console
4) To override default credentials we can configure credentials in the application.properties file.

admin
admin@123

5) Create Rest Controller class with required method


Rest Client To access Secured REST API
@Service
public class WelcomeService {
http://localhost:8080
public void invokeWelcomeApi() {
RestTemplate rt = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("admin", "admin@123");
HttpEntity<String> reqEntity = new HttpEntity<>(headers);
ResponseEntity<String> responseEntity = rt.exchange(apiUrl, HttpMethod.GET, reqEntity, String.class);
String body = responseEntity.getBody();
System.out.println(body);
}
public void invokeWelcome() {
WebClient webClient = WebClient.create();
String block = webClient.get()
.uri(apiUrl)
.headers(headers -> headers.setBasicAuth("admin", "admin@123"))
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println(block);
}
}
Mono & Flux Objects
Mono means single object
Flux means stream of objects
3) Create a spring boot application with the following 3 dependencies

web-starter
b) webflux
c) lombok

--------------------------------
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomerEvent {
private String name;
private Date createDate;
}
---------------------------------
@RestController
public class CustomerRestController {
@GetMapping(value = "/event", produces = "application/json")
public ResponseEntity<Mono<CustomerEvent>> getEvent() {
CustomerEvent event = new CustomerEvent("Ashok", new Date());
Mono<CustomerEvent> customerMono = Mono.just(event);
return new ResponseEntity<Mono<CustomerEvent>>(customerMono, HttpStatus.OK);
}
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<Flux<CustomerEvent>> getEvents() {
// creating binding object with data
CustomerEvent event = new CustomerEvent("Ashok", new Date());
creating stream for binding object
Stream<CustomerEvent> customerStream = Stream.generate(() -> event);
// create flux object using stream
Flux<CustomerEvent> cflux = Flux.fromStream(customerStream);
// setting response interval
Flux<Long> intervalFlux = Flux.interval(Duration.ofSeconds(5));
// combine interval flux and customer event flux
Flux<Tuple2<Long, CustomerEvent>> zip = Flux.zip(intervalFlux, cflux);
// Getting Tuple value as T2
Flux<CustomerEvent> fluxMap = zip.map(Tuple2::getT2);
//sending response
return new ResponseEntity<>(fluxMap, HttpStatus.OK);
}
}

1) Angular is a client-side framework developed by Google.


The Angular framework is developed based on TypeScript.
Angular is mainly used for Single Page Applications
Angular supports multiple devices (Mobiles & Desktops)
Angular supports multiple browsers
Angular is free and open source
7) Angular JS and Angular both are not the same
8) From Angular 2 version onwards it is called as Angular Framework
Note: The current version of Angular is 14

Angular Building Blocks

1) Component
2) Metadata
3) Template
4) Data Binding
Module
6) Service
7) Dependency Injection
8) Directive
9) Pipes
10) An Angular application is a collection of components. In components, we will write logic to send data to
template and capture data from template. Components are TypeScript classes.
11) Metadata is nothing but data about the data. It provides information about components.
12) The template is a view where we will write our presentation logic. In an Angular application, the template is an HTML.

file. Every Component contains its own Template.


Data Binding is the process of binding data between component property and view element in template.
file.
14) Module is a collection of components, directives, and pipes.
15) Service means it contains re-usable business logic. Service classes we will inject in Components using
Dependency Injection.
16) Dependency Injection is the process of injecting a dependent object into a target object. In Angular
Application services will be injected into components using DI.
Directives are used to manipulate DOM elements.
Pipes are used to transform the data before displaying

Environment Setup For Angular Applications


1) Install Node JS
2) Install TypeScript
3) Install Angular CLI
4) Install Visual Studio Code IDE
The Angular 2+ framework is available as a collection of packages, these packages are available in 'Node'.
To use those packages, 'npm' (Node Package Manager) is a must.
a. URLhttps://nodejs.org/en/
20) After installing the node software, open cmd and type node -v. It should display the node version number then
Installation is successful.
21) The Angular framework itself is developed based on TypeScript. In Angular applications, we will write code.
using TypeScript only.
22) We can install Typescript using Node Package Manager (npm). Open command prompt and execute
below command to install TS.
a. $ npm install -g typescript
23) After TypeScript installation is complete, we can verify the version number using the command below in cmd.
If it displays the version number, then the installation is successful.
a. $ tsc -v
24) Install Angular CLI software using the command below in TypeScript.
a. $ npm install @angular/cli -g
25) Check angular installation using the command below
a. $ ng v
Download and install VS code IDE
https://code.visualstudio.com/download
1) Note: We are done with the angular setup... let's start building angular applications. What is Unit testing?
It is the process of testing unit amount of work
3) When we implement code, we need to test whether that code is working or not.
4) With the help of unit testing we can identify issues in the code
To perform Unit testing we will use Junit
Junit is an open source & free framework to perform unit testing for java applications

Mocking
Mocking is the process of creating a substitute object for the real object.
Using Mock Objects we can perform isolated unit testing

@Service
public class WelcomeService {
public String getMsg() {
Good Morning
return msg;
}
}
-----------------------------------------------------------
@RestController
public class WelcomeRestController {
@Autowired
private WelcomeService service;
@GetMapping("/welcome")
public String welcomeMsg() {
String msg = service.getMsg();
return msg;
}
}
@WebMvcTest(value = WelcomeRestController.class)
public class WelcomeRestControllerTest {
@MockBean
private WelcomeService service;
@Autowired
private MockMvc mockMvc;
@Test
public void welcomeMsgTest() throws Exception {
defining mock object behavior
when(service.getMsg()).thenReturn("Welcome to Ashok IT");
// preparing request
MockHttpServletRequestBuilder reqBuilder = MockMvcRequestBuilders.get("/welcome");
sending request
MvcResult mvcResult = mockMvc.perform(reqBuilder).andReturn();
get the response
MockHttpServletResponse response = mvcResult.getResponse();
// validate response status code
int status = response.getStatus();
assertEquals(200, status);
}
}

Create Spring Boot Application with the following starters

a. web-starter
b. data-jpa
c. h2
d. project lombok
e. devtools
Create Entity class
@Data
@Entity
Table name = "BOOK_DTLS"
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
BOOK_ID
private Integer bookId;
Column(name = "BOOK_NAME")
private String bookName;
BOOK_PRICE
private Double bookPrice;
}

Create Repository interface


public interface BookRepository extends JpaRepository<Book, Serializable>{
}
Create Service interface and implementation class

public interface BookService {


public String upsertBook(Book book);
public List<Book> getAllBooks();
}
@Service
public class BookServiceImpl implements BookService {
private BookRepository repository;
public BookServiceImpl(BookRepository repository) {
this.repository = repository;
}
@Override
public String upsertBook(Book book) {
repository.save(book);
Record Inserted
}
@Override
public List<Book> getAllBooks() {
return repository.findAll();
}
}
Create Rest Controller
@RestController
@CrossOrigin
public class BookRestController {
@Autowired
private BookService service;
@PostMapping("/book")
public ResponseEntity<String> addBook(@RequestBody Book book) {
String msg = service.upsertBook(book);
return new ResponseEntity<>(msg, HttpStatus.CREATED);
}
@GetMapping("/books")
public ResponseEntity<List<Book>> getAllBooks() {
List<Book> allBooks = service.getAllBooks();
return new ResponseEntity<>(allBooks, HttpStatus.OK);
}
}
Configure the following properties in the application.properties file.

jdbc:h2:mem:testdb
sa
sa
org.h2.Driver
update
true
Run the boot application and insert the data using POST Request
Create Angular application
$ ng new bookapp
Create Book class to represent json response in object format
$ ng generate class Book
export class Book {
number
string
number
constructor(a:number,b:string,c:number){
this.bookId = a;
b
this.bookPrice = c;
}
}
Import HttpClientModule & FormsModule in AppModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule, HttpClientModule
],
providers: [],
[AppComponent]
})
export class AppModule { }

Write REST Call logic in AppComponent


import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { Book } from './book';
@Component({
app-root
./app.component.html
./app.component.css
})
export class AppComponent {
msg
book:Book = new Book(1,"Spring", 200);
Book[] = [];
constructor(@Inject(HttpClient) private http: HttpClient) {}

getData() {
this.http.get<Book[]>("http://localhost:8080/books", {responseType: 'json'})
.subscribe(data => {
this.books = data;
});
}
onInsertClick() {
this.http.post("http://localhost:8080/book", this.book, {responseType:"text"})
.subscribe(data => {
this.msg = data;
});
}
}
Write presentation logic in template

Angular UI + Boot REST API


<form>
Book ID : <input type="text" name="bookId" [(ngModel)]="book.bookId"/><br/>
Book Name
<input type="text" name="bookPrice" [(ngModel)]="book.bookPrice"/><br/>
Save Book
Message
</form>

<div>
Book Details
<input type="button" value="Get Data" (click)="getData()"/>
<table border="1">
<tr>
Book Id
Book Name
Book Price

<tr *ngFor="let book of books">


<td>{{book.bookId}}</td>
{{book.bookName}}
{{book.bookPrice}}
</tr>
translatedText

Run the Angular Application

You might also like