[go: up one dir, main page]

0% found this document useful (0 votes)
10 views87 pages

Chapter 3

Chapter III discusses the deployment of microservices using Docker, detailing the steps for application packaging, building Docker images, and executing containers. It outlines the development environment setup using tools like Net Beans IDE, Spring Framework, and Maven, and provides guidance on creating a sample REST application with Spring Boot. The chapter also covers testing the application with Postman and introduces Domain-Driven Design (DDD) principles for implementing microservices.

Uploaded by

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

Chapter 3

Chapter III discusses the deployment of microservices using Docker, detailing the steps for application packaging, building Docker images, and executing containers. It outlines the development environment setup using tools like Net Beans IDE, Spring Framework, and Maven, and provides guidance on creating a sample REST application with Spring Boot. The chapter also covers testing the application with Postman and introduces Domain-Driven Design (DDD) principles for implementing microservices.

Uploaded by

reguvel07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Chapter-III

Deployment
Deployment
 Micro services deployment with Docker deals with 3
parts. They are:
1. Application packaging, eg: JAR.
2. Building Docker image with a JAR and dependencies
using a Docker instruction file, the Docker file, and
command “docker build”.
3. Docker container execution from this newly built
image using command “docker run”.
Setting the Development Environment
Tools & Technologies required :
1. Net Beans IDE.
2. Spring Framework.
3. Maven tool.
4. Jetty embedded server.
5. Spring Boot configuration.
6. Postman extension of Chrome.
Net Beans IDE installation and
setup
Download Net Beans IDE and its supported bundles.
 The required packs and runtimes are denoted as already
installed, which is shown as:
 After downloading the installation, execute the installer file.
Accept the license agreement as shown below:
 Once the Net Beans IDE is installed, start the Net Beans IDE.
Net Beans IDE should look as follows:
Maven is a Java build tool available in the Net Beans IDE.
Even Gradle tool can be used.
Start a new Maven project to build our first REST
application.
The steps for creating a new empty Maven project are:
1. Click on New Project (Ctrl + Shift + N) under the File
menu. It will open the New Project wizard.
2. Select Maven from the Categories list. Then, select
POM Project from the Projects list, as shown in
following screenshot:
Now click on Next button.
3. Now, enter the project name as 6392_chapter2. Also, enter the other
properties as shown in the following screenshot:
 After finishing all the preceding steps, Net Beans will
display a newly created Maven project.
 You will use this project for creating the sample rest
application using Spring Boot.
4. To use Java 9 as a source, set Source/Binary Format
to 9, as shown in the following screenshot:
5. Go to Build, click Compile and make sure that Java
Platform is set as JDK 9 (Default) as follows:
6. Similarly, you can add two new modules named lib
and rest in the Modules folder by opening the right-
click menu and then selecting the Create New
Module option.
7. This time you should select Maven from the
Categories list and Java Application from Projects
list in New Project dialog box.
Spring Boot Configuration
 Amazing Spring tool created by Pivotal, released in April
2014.
 Spring Boot is preconfigured to make production-ready web
applications very easily.
 The default packaging option is JAR, used for micro services
development.
 Spring Cloud - wrapper on top of Spring Boot.
Sample REST application
 Create two modules — lib and rest.
 The lib module will provide the models or any supported
classes to the rest module.
 The rest module will include all the classes that are required
to develop the REST application and it will also consume the
model classes defined in the lib module.
 Both the lib and rest modules are maven modules and
their parent module is our main project
“6392_chapter2”.
 The “module-info.java” file is an important class that
governs the access of its classes.
 We'll make use of requires, opens, and exports to use
the spring modules and establish the provider-
consumer relationship between the lib and rest
modules of our REST application.
The steps for adding Spring Boot to the main project are:
1. Open the pom.xml file that is available under
6392_chapter2 | Project Files to add Spring Boot to the
sample project. It is shown as:
Contd…
Contd…
Contd…

• It is observe that we have defined our two modules lib and


rest in parent project pom.xml .
2. If you are adding these dependencies for the first time,
you need to download the dependencies by right-
clicking on the Dependencies folder under the
6392_chapter2 project in the Projects pane, as shown in
the following screenshot:
3. Similarly, to resolve the project problems, right-click on the
Net Beans project 6392_chapter2 and opt for the Resolve
Project Problems.... It will open the dialog box shown as
follows:

Click on the Resolve... button to resolve the issues:


4.If you are using Maven behind the proxy, then update the
proxies in settings.xml in Maven home directory.
 If you are using the Maven bundled with Net Beans then
use:
<NetBeansInstallationDirectory>\java\maven\conf\settings.xml .
 Now, you may need to restart the Net Beans IDE.
 The preceding steps will download all the required
dependencies from a remote Maven repository if the
declared dependencies and transitive dependencies are
not available in a local Maven repository.
 If you are downloading the dependencies for the first
time, then it may take a bit of time, depending on your
internet speed.
Sample REST program
Here, we define the domain models in the lib module and
API related classes in the rest module.
The pom.xml file of the lib module is shown as:
The pom.xml of the rest module is shown as:

Here, the spring-boot-starter-web dependency is used for


developing the standalone executable REST service.
Now, We add the following module-info.java classes in
the lib and rest modules in their default package,
respectively.
The module-info.java file in the lib module is shown as:

Here, we are exporting the com.packtpub.mmj.lib.model


package to com.packtpub.mmj.rest, which allows access
of the lib model classes to the rest module classes.
Now, the module-info.java file in the lib module is:
Here, we add all the required spring and lib packages
using the requires statement, which enables the rest
module classes to use classes defined in the spring and
lib modules.
 Also, we're exporting the com.packt.mmj.rest and
com.packt.mmj.rest.resources packages.
We are ready with Spring Boot in Net Beans IDE, we
could create a sample web service.
Now, create a Math API that performs simple
calculations and generates the result as JSON.
We shall discuss how we can call and get responses
from REST services.
The service will handle the GET requests for
/calculation/sqrt or /calculation/power and so on.
The GET request should return a 200 OK response with
JSON in the body that represents the square root of a given
number. It will look like this:

The input field is the input parameter for the square root
function, and the content is the textual representation of the
result.
Now, we can create a resource representation class to
model the representation by using Plain Old Java
Object (POJO) with fields, constructors, setters, and
getters for the input, output, and function data.
We create it in the lib module shown as:
Writing the REST controller class
Now, we'll create a REST controller to handle the Calculation
resource.
The controller handles the HTTP requests in the Spring
RESTful web service implementation.

The @RestController annotation


It is a combination of @Controller and @ResponseBody, and
because of it, a class returns a domain object instead of a view.
Here we can see that the CalculationController class handles
GET requests for /calculation by returning a new instance of
the calculation class.
We will implement two URIs for a Calculation resource—the
square root (Math.sqrt() function) as the /calculations/sqrt
URI, and power (Math.pow() function) as the
/calculation/power URI.
The @RequestMapping annotation
 The @RequestMapping annotation is used at class level to map
the /calculation URI to the CalculationController class, (i.e;) it
ensures that the HTTP request to /calculation is mapped to the
CalculationController class.
 Here, the request mapping /calculation/sqrt is mapped to the
sqrt() method and /calculation/power is mapped to the pow()
method.
 The @RequestMapping annotation maps all the HTTP request
methods by default.
 If we consider to write a @RequestMethod annotation to use the
POST method by:
@RequestMapping(value = "/power", method = POST)
 For passing the parameters along the way, the sample
demonstrates both request parameters and path parameters using
annotations @RequestParam and @PathVariable, respectively.
The @RequestParam annotation
@RequestParam is responsible for binding the query
parameter to the parameter of the controller's method.
Default values for query parameters could be set using the
defaultValue property of @RequestParam, shown as:
@RequestParam(value="base", defaultValue="2“)
Here, if the user does not pass the query parameter base, then
the default value 2 would be used for the base.
If no defaultValue is defined, and the user doesn't provide
the request parameter, then RestController returns the
HTTP status code 400 with the message “Required String
parameter 'base' is not present”.
It always uses the reference of the first required parameter
if more than one of the request parameters is missing.
It is shown as:
{
"timestamp": 1464678493402,
"status": 400,
"error": "Bad Request",
"exception":
"org.springframework.web.bind.MissingServletRequest
ParameterException",
"message": "Required String parameter 'base' is not
present",
"path": "/calculation/power/"
}
The @PathVariable annotation
Helps us to create the dynamic URIs.
Allows you to map Java parameters to a path parameter.
Works with @RequestMapping where the placeholder is
created in URI then the same placeholder name is used
either as a PathVariable or a method parameter.
Code of CalculationController resource, where we have
implemented to REST endpoints, is shown below:
Contd…
Contd…

Here, we are exposing only the power and sqrt functions for
the Calculation resource using URI /calculation/power
and /calculation/sqrt.
Here, due to Spring's HTTP message converter support, the
Calculation object gets converted to JSON automatically.
You don't need to do this conversion manually.
Execution
Create a RestSampleApp class with the annotation
SpringBootApplication.
The main() method uses Spring Boot's SpringApplication.run()
method to launch an application.
We annotate the RestSampleApp class with the
@SpringBootApplication annotation that implicitly adds the
following tags:
 The @Configuration annotation tags the class as a source of bean
definitions for the application context.
 The @EnableAutoConfiguration annotation indicates that Spring
Boot is to start adding beans based on class path settings, other
beans, and various property settings.
 The @EnableWebMvc annotation is added if Spring Boot finds
spring-webmvc on the class path.
It treats the application as a web application and activates key
behaviors such as setting up DispatcherServlet.
 The @ComponentScan annotation tells the Spring to look for other
components, configurations, and services in the package shown
below:

 This web application is 100% pure Java and we don’t deal with
configuring any plumbing or infrastructure using XML; instead, it
uses the Java annotation that is made even simpler by Spring Boot.
 So, there wasn't a single line of XML except pom.xml for Maven and
even a web.xml file.
Adding a Jetty-embedded server
We need to add a Jetty application container dependency to
support the Jetty web server.
Jetty allows you to read keys or trust stores using class paths.
A relative section on pom.xml of module rest is shown below:
Running the Maven tool
 The steps that should be followed to use the Maven tool to
execute the generated JAR file are:
1. Right-click on the pom.xml file .
2. Select Run Maven | Goals... from the pop-up menu, then it
will open the dialog. Now type spring-boot:run in the
Goals field.
Here we have used the released version of Spring Boot in
the code.
If you are using the snapshot release, you can check the
Update Snapshots checkbox.
To use it in the future, type spring-boot-run in the
Remember as field.
3. Now, we can directly click Run Maven | Goals | spring-
boot-run to execute the project. It is shown below:

4. Click OK to execute the project.


Executing with the Java command
 We must make sure that Java and JAVA_HOME is set to Java 9
before executing the commands.
 The steps for execution are:
1. To build the JAR file, perform the mvn clean package
command from the Command Prompt from the parent
project root directory (6392_chapter2).
mvn clean package
 Here, clean and package are Maven goals.
2. It creates the JAR files in a respective target directory. We'll
execute the JAR files generated in the 6392_chapter2\rest\
target directory.
 A JAR file can be executed using the following command:
java -jar rest\target\rest-1.0-SNAPSHOT-
exec.jar
Testing with Postman Chrome extension
We use the Postman Chrome application or any other REST Client
to test our sample REST application, as shown below:
Once the application is started, you can type the Calculation
REST URL for sqrt and value 144 as the path parameter.
It is shown in the following screenshot:
The URL is entered in the URL (enter request URL here) input
field of the Postman extension.
By default, the request method is GET. We use the default value
for the request method, as we have also written our RESTful
service to serve the request GET method.
Once we are ready with the input data as mentioned earlier, we
can submit the request by clicking the Send button.
We can see in the screenshot that the response code 200 is
returned by our sample REST service and also find the Status
label in the screenshot to see the 200 OK code.
 A successful request also returns the JSON data of the
Calculation resource, shown in the Pretty tab in the screenshot.
The returned JSON shows the sqrt method value of the function
key.
It displays 144 and 12.0 as the input and output lists respectively.
We also test our sample REST service for calculating the power
function.
 We input the following data in the Postman extension:
URL: http://localhost:8080/calculation/power?
base=2&exponent=4
Request method: GET
Here, we are passing the request parameters base and exponent
with values of 2 and 4, respectively.
It returns the following JSON:
It returns the preceding JSON with a response status of 200, as
shown in the following screenshot:
Positive test scenarios
In the following table, all the URLs start with http://localhost:8080
Negative Test Scenarios
In this table, all the URLs start with http://localhost:8080
Domain-Driven
Design(DDD)
 DDD is one of the software design practices that we'll
explore in various theories and practical examples.
 The combination of domain and software design offers
a software design methodology known as DDD.
 DDD makes design and development work together.
 It is a key design practice that helps to design the micro
services of the developing product.
 It provides the ability to develop software
continuously, while keeping the design up to date based
on feedback received from the development.
Implementing a Micro service
Implementing a micro service is done in 3 steps.
They are:
1. Overview of the project.
2. Developing and implementing the micro service.
3. Testing.
Example
Consider a sample project of online table reservation
system (OTRS).
Now we'll implement the OTRS project with the 3 steps
mentioned above.
OTRS overview
 There are many micro services that can be defined in
OTRS.
 We shall focus mainly on 3 micro services. They are:
i. Restaurant service : This service provides the
functionality for the restaurant resource—create, read,
update, delete (CRUD) operation and searching based
on criteria.
 It provides the association between restaurants and tables.
 Restaurant would also provide access to the Table entity.
ii. User service : As the name suggests, this service allows
the end user to perform CRUD operations on User
entities.
iii. Booking Service : This makes use of the Restaurant
service and User service to perform CRUD operations on
booking.
 It will use restaurant searching and its associated table
lookup and allocation based on table availability for a
specified time duration.
 It creates the relationship between the restaurant/table
and the user, shown in the following dig:
Developing and implementing
micro services
Here, we will use the domain-driven implementation
and approach to implement the micro services using
Spring Cloud.
The key artifacts are:
i. Entities : These are categories of objects that are
identifiable and remain the same throughout the states
of the product/services.
 These objects are not defined by their attributes, but
by their identities and threads of continuity.
 Entities have traits such as identity, a thread of
continuity, and attributes that do not define their
identity.
ii. Value objects (VOs) : These have the attributes and no
conceptual identity.
 A best practice is to keep VOs as immutable objects.
 In the Spring Framework, entities are pure POJOs.
iii. Service objects : These are common in technical
frameworks and are also used in the domain layer in
domain-driven design.
 The purpose of service object is to provide the
behavior to the domain.
 Service objects may provide one or more related
behaviors to one or more entities or VOs.
 It is best practice to define the services explicitly in the
domain model.
iv. Repository objects : A repository object is a part of the
domain model that interacts with storage, such as
databases, external sources, etc…, to retrieve the
persisted objects.
 When a request is received by the repository for an
object reference, it returns the existing object reference.
 If the requested object does not exist in the repository,
then it retrieves the object from storage.
Each OTRS micro service API represents a RESTful web
service.
The OTRS API uses HTTP verbs such as GET, POST, and
so on, and a RESTful endpoint structure.
Request and response payloads are formatted as JSON.
 If required, XML can also be used.
Restaurant micro
service
The Restaurant micro services will be exposed to the
external world using REST endpoints for consumption.
We'll find the following endpoints in the Restaurant micro
service example. One can add as many endpoints as per
the requirements:
1. Endpoint for retrieving restaurant by ID is shown as:
2. Endpoint for retrieving all the restaurants that matches
the value of query parameter Name is shown as:
3. Endpoint for creating new restaurant is shown as:

Similarly, we can add various endpoints and their


implementations.
For demonstration purposes, we'll implement the
preceding endpoints using Spring Cloud.
OTRS implementation
 Consider the following OTRS modules:
eureka-service
restaurant-service
user-service
booking-service
 The root pom.xml file will look like this:
Contd…
Contd…
Controller class : The RestaurantController class uses the
@RestController annotation to build the Restaurant service
endpoints.
 The @RestController is a class-level annotation that is used
for resource classes.
 It is a combination of the @Controller and
@ResponseBody annotation. It returns the domain object.

API versioning : There are various ways of managing API


versions - one of these is using the version in the path, or
some people use the HTTP header.
 The HTTP header can be a custom request header or an
accept header to represent the calling API version.
 It is shown in the following screenshot:
Contd…
Service classes : The RestaurantController class uses the
RestaurantService interface.
 RestaurantService is an interface that defines CRUD and some
search operations, shown as follows:

 Now, we can implement the RestaurantService we have just


defined, that extends the BaseService class you created in the
last chapter.
 We use the @Service Spring annotation to define it as a service,
Repository classes : The RestaurantRepository interface defines
two new methods - the containsName and findByName methods.
 It also extends the Repository interface, shown as:

 The Repository interface defines three methods: add, remove,


and update.
 It also extends the ReadOnlyRepository interface, shown as:
 The ReadOnlyRepository interface definition contains the get and
getAll methods, which return Boolean values, entity, and collection
of entity, respectively.
 It is useful if you want to expose only a read-only abstraction of the
repository, shown as:

 The Spring Framework makes use of the @Repository annotation


to define the repository bean that implements the repository.
 In case of RestaurantRepository, we can see that a map is used in
place of the actual database implementation, that keeps all entities
saved in memory only.
 So, when we start the service, we find only two restaurants in
memory and we can use JPA for database persistence.
 This is the general practice for production-ready
implementations:
Contd…
Entity classes :
 The Restaurant entity, which extends BaseEntity, is defined
as follows:
 The Table entity, which extends BaseEntity, is defined as
follows:
 The Entity abstract class is defined as follows:
 The BaseEntity abstract class extends the Entity abstract
class, is defined as follows:
Eureka service : The Eureka service registers/lists all micro
services that have been configured by the Eureka client.
 Once you start your service, it pings the Eureka service
configured in your application.yml and once a connection is
established, the Eureka service registers the service.
 It also enables the discovery of micro services through a uniform
way to connect to other micro services.
 we can create a Eureka service in the following 3 steps:
1. Maven dependency : It needs a Spring Cloud dependency and a
startup class with the @EnableEurekaApplication annotation in
pom.xml, shown as follows:
2. Startup class: The startup class App will run the Eureka
service seamlessly by just using the
@EnableEurekaApplication class annotation, shown
below:
3. Spring configuration :The Eureka service also needs the
following Spring configuration for the Eureka server
configuration:

Eureka Client :
 Connection between the Eureka server and the client is
established.
 Our services can use the following Spring configuration to
configure the Eureka client.
 Add the following configuration in the Restaurant, Booking, and
User services (restaurantservice\src\main\resources\
application.yml):
eureka:
client:
serviceUrl:
defaultZone:http://localhost:8761/eureka/

Booking & User services


 We can use the RestaurantService implementation to develop
the Booking and User services.
 The User service can offer the endpoint related to the User
resource with respect to CRUD operations.
 The Booking service can offer the endpoints related to the
booking resource with respect to CRUD operations and the
availability of table slots.
Execution
 To see how the code works, we need to first build it and then execute it.
 We'll use a Maven clean package to build the service JARs.
 Now, to execute these service JARs, simply execute the following
command from the project home directory:
java -jar <service>/target/<service_jar_file>
 Here are some examples:
java -jar restaurant-service/target/restaurant-service.jar
java -jar eureka-service/target/eureka-service.jar
 We will execute our services in the following order from the project home
directory.
 The Eureka service should be started first; the order of the last three
micro services can be changed, shown as:
java -jar eureka-service/target/eureka-service.jar
java -jar restaurant-service/target/restaurant-service.jar
java -jar booking-service/target/booking-service.jar
java -jar user-service/target/user-service.jar
Testing
 To enable testing, add the following dependency in the
pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>

 The RestaurantControllerIntegrationTests class, uses the


@SpringApplicationConfiguration annotation to pick the
same configuration that Spring Boot uses, is shown as:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RestaurantApp.class)
public class RestaurantControllerIntegrationTests extends
AbstractRestaurantControllerTests {
}
 An abstract class to write our tests is shown below:
Contd…

 Finally, the RestaurantControllerTests class, which extends the


previously created abstract class and also creates the
RestaurantService and RestaurantRepository implementations,
shown below:
Contd…
Contd…

You might also like