Category Archives: Core Java

Spring Boot and Microservices

Over the last few months, I have worked on Spring Boot and tried to collect my knowledge around Microservices. I was discussing lot of this with my friends and one friend did suggest me to write a book. Initially I was little hesitant to write a book about something I was learning. But also the whole point of learning is to teach someone at some point of time.

Spring Boot and Microservices

So I took this as a challenge to write a book about Spring Boot and Microservices. Initially I created series of posts and posted on this blog to see how much it could benefit people. And now to make it easy for every one, I have collected all this information and wrote an ebook. This ebook Spring Boot and Microservices is free to download. I hope this will help people to understand the concepts of Microservices and my example can help them to head start the building their projects.

Spring Boot and Microservices

What’s next?

Where do we go from here? There are a lot of questions about the next strategy for Spring Boot and Microservices. What I have covered in this book, is a tiny portion of big picture. There is lot of options like scaling the service, adding a health check for the service, and deploying the service on the cloud with automation. But for right now, I just want to take a break from thinking about this and I will come up with a next plan soon.

Till that time, you can download, read, and send me your feedback about the book. It would be great if you could leave a review for the book here.

If you have any questions, please leave your comments on this blog and I will try my best to answer them.

How to deploy Spring Boot Application on docker – Part IX

In this post, I show how to deploy a spring application in a docker container.

What is docker

Docker is a container platform delivered by a company named “Docker Inc.” It can be used by developers, operators, and enterprise users to deliver and use packaged software. Docker has something called a container. A container can be a virtual machine (VM) in lay man’s terms, but still a little different from VM. Container contains packaged software delivered in a way that it can be run isolated on a shared operating system. As per official definition – Unlike VMs, the container does not bundle a full operating system – only libraries and settings required to make the software work are needed.

In this demo, we will use our spring boot application built throughout from Part I to Part VIII.

I am using Windows Platform Toolbox for docker to build my docker containers. 

We will build a container with MySQL database deployed and another container where we will deploy spring boot application. This spring boot application container will connect to MySQL database container at runtime. The process is a little complicated, but once you get your hands on the docker container, it becomes very straight forward to understand. Also for this post, I will not explain anything about spring boot application. You should review all the previous posts I have written explaining how to build and deploy spring boot application on an embedded tomcat.

Once we know about docker, it is easy to deploy an application in docker.

Building a docker container with MySQL

Few things to remember

  1. Make sure your spring boot application is working with MySQL database before you build a container.
  2. If your application contains user administration and password, make sure you have a super administrator whose password you can insert in the database with password_hash. This is specifically true for the application we will be deploying in the docker container.

For most standard applications (like MySQL, java 8, spring-boot), there are a number of images available in the docker hub. When we will run our docker container for the database, the docker shell will pull the version of that application from the hub to build a container. We will not be creating any new or blank docker image. To run a docker container with mysql version 5.6, we will use below command.



docker run --name benefitsmysql -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -e MYSQL_DATABASE=benefitsmysql -p 3308:3306 -d mysql:5.6

 

  • The name of our docker container is benefitsmysql.
  • We are not using any password. This is not recommended for production code, I am just doing this for demo purposes.
  • The database name is benefitsmysql.
  • Also this database is running at port 3308 to 3306 of localhost machine.
  • -d to tell Docker to daemonize the container and keep it running.
  • mysql:5.6 to download MySQL 5.6 Server image from Docker public repo

Once this is started, there are couple of ways you can verify if we are able to connect to this database or not.

Get the ip address of this container host with command docker-machine ip . Now in mysql administrator workbench, access the mysql server with ip address and port 3308 and see if you can access the database.

Another way on docker shell terminal – use this command docker exec -it benefitsmysql -l , this will connect you as a root to the shell where mysql is installed. And then you can use mysql as regular command to access mysql.

To run our Spring boot application successfully, once you access mysql, create the following tables:



use benefitsmysql;

create table companyprofile (id int not null auto_increment, establisheddate date, status varchar(50),corporationtype varchar(50), primary key(id));

create table company(id int not null auto_increment, name varchar(255), statusid int, type varchar(255), ein varchar(50), companyprofileid int, primary key(id), foreign key(companyprofileid) references company(id));

create table userprofile(id int not null auto_increment, dob date, doh date, maritalstatus varchar(50),sex varchar(50),ssn varchar(50),weight varchar(50), height varchar(50),employmentstatus varchar(50), terminationdate date, primary key(id));

create table user(id int not null auto_increment, createdate date, email varchar(255),firstname varchar(255), middlename varchar(255), lastname varchar(255),username varchar(100),jobtitle varchar(255),password_hash text,enabled tinyint(4), userprofileid int, primary key(id), foreign key(userprofileid) references userprofile(id));

create table role(id int not null auto_increment, role varchar(255), primary key(id));

create table user_role(user_id int not null, role_id int not null, primary key(user_id, role_id));

 

Building a docker image for Spring Boot Application along with mysql

To dockerize my spring boot application, we will use a maven plugin to build a docker image.


<plugin>
		<groupId>com.spotify</groupId>
            	<artifactId>docker-maven-plugin</artifactId>
            	<version>1.0.0</version>
            	<configuration>
                	<imageName>${docker.image.prefix}/benefits</imageName>
                	<dockerHost>https://192.168.99.100:2376</dockerHost>
                	<dockerCertPath>C:\Users\Yogesh Mali\.docker\machine\machines\default</dockerCertPath>
                	<dockerDirectory>src/main/docker</dockerDirectory>
                	<resources>
                    	<resource>
                        	<targetPath>/</targetPath>
                        	<directory>${project.build.directory}</directory>
                        	<include>${project.build.finalName}.jar</include>
                    	</resource>
                	</resources>
            	</configuration>
	</plugin>

I am passing dockerDirectory where Dockerfile will be stored to build our image. Also another change I have made to my original pom file, is that i have added packaging as jar.


<groupId>com.betterjavacode</groupId>
	<artifactId>Benefits</artifactId>
	<packaging>jar</packaging>
	<version>0.0.1-SNAPSHOT</version>
  .................
  <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <configuration>
          <mainClass>com.betterjavacode.benefits.Application</mainClass>
      </configuration>
      <executions>
          <execution>
              <goals>
                 <goal>repackage</goal>
              </goals>
          </execution>
      </executions>
  </plugin>

I have also changed in my application.properties to point to mysql database container by updating database url with ipaddress of docker container.

spring.datasource.url=jdbc:mysql://192.168.99.100:3308/benefitsmysql

My Dockerfile to build a docker image is as below:


FROM java:8
VOLUME /tmp
ADD Benefits.jar Benefits.jar
EXPOSE 8443
RUN bash -c 'touch /Benefits.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/Benefits.jar"]

Basically this will build a Benefits.jar using java 8 and will expose port 8443 that I can use to access my application.

Now build a new docker container image by using maven goal as

mvn clean package docker:build

To run the application

docker run -p 8443:8443 --name benefits --link benefitsmysql:mysql -d containerid

This will execute the jar built within that container. Important to note here is --link as it links other container where we have mysql server deployed. So we are linking two containers and we will call the database from our spring boot application container. The same command can be used little differently to see the detail execution log as below

docker run -p 8443:8443 --name benefits --link benefitsmysql:mysql -it containerid

 

Executing the application

Once the application starts successfully, we will access our application with url https://192.168.99.100:8443/home , this will look like below:

How to deploy on docker container

Another note – Make sure to update IP addess in all angular js references.

In this post, we showed how we can deploy Spring boot application connected to MySQL on a docker container. Code for this post will be available on GitHub repository here

References

To write my post, I used the following references

  1. Docker
  2. Connection refused error
  3. Spring Boot docker

 

Microservices – A Primer

In this post, I cover a primer about microservices.

What is Microservices? A Primer about Microservices

Wikipedia definition says

Microservices is a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely coupled services.

Firstly, there is no official definition of Microservices by industry standards. It’s a recent phenomenon in the software industry to architect the new software which should be lightweight, easier to deploy, and scale, easier to refactor individually, and could work independently.

However, to understand in detail, you can definitely read Martin Fowler’s Microservices or Chris Richardson’s Microservices.

Secondly, microservices are small services that can run independently but can also easily communicate with other services.

Microservice Architecture vs Monolithic Architecture

In a traditional monolithic architecture style, there is a single application with a single code base. An application contains a number of modules that are interrelated and can have external dependencies. It’s a multi-tier enterprise application and has been used to build software for long.

Above all, the microservice architecture style was born out of a need to build an application that could easily be supported for mobile applications. The older style was not easy to support for mobile and new generation way to the handling of data. Any large enterprise application can be easily built using the microservices architecture style. A famous example is NETFLIX.

How to identify the Microservice Architecture Pattern?

A simple ground rule of the microservice architecture pattern is to build a standalone service that can be run without depending on any other service. In other words, a large application can have more than one service talking to each other, communicating with their own databases, but still performing the business logic. Databases are used to ensure loose coupling of services.

For instance, a large enterprise e-commerce application can consist of the following services

  1. Backend service REST API to manage data
    1. Account Service
    2. Shipment Service
    3. Inventory Service
  2. Runtime service to handle runtime and backend data to process business logic
  3. Logging service
  4. Error Handling service
  5. Session service

Additionally, UI for the e-commerce application can be built independently to use backend services to show/edit data.

By standards, there are few rules to identify microservices patterns

  1. Decomposition by business capability
  2. Database per service pattern
  3. API gateway pattern
  4. Client-side discovery and Server-side discovery

Pros and Cons of Microservices

Pros

  1. Deployability – Easier to deploy and one can deploy them independently, without affecting other services.
  2. Reliability – A fault in the service can only bring down that service. Depending on the handling of the fault in the application, the rest of the application can still continue to work.
  3. Scalability – Similarly, the scaling of each microservice will depend on requirements using clusters and grids.
  4. Availability – Dispatching the patch or newer version of service requires less downtime compared to regular monolithic applications.
  5. Management – Easier to manage
  6. Design and Development – Each service helps the developer to manage the service easily without worrying about other services.

Cons

  1. Performance – All services involved in the application have to communicate with each other over the network and that could hamper the performance.
  2. Testability – Automated tests are harder to manage and run.
  3. Memory usage – Possible duplicate data across services and a lot of duplication in the cache.

References

In conclusion, I covered a primer about microservices. If you want to read more about Microservices at following links:

  1. Microservices by Chris Richardson
  2. Microservices by Martin Fowler
  3. Stackoverflow post about microservices

Lastly, if you enjoyed this post, subscribe to my blog.

 

Design Pattern – Prototype Pattern – Part VI

In this post, I want to show how to use Prototype design pattern. If you want to read about previous posts related to design patterns, series of posts about design patterns are

  1. Introduction to design patterns
  2. Singleton Pattern
  3. Factory Pattern
  4. Abstract Factory Pattern
  5. Builder Pattern

The prototype design pattern will cover the creation design pattern that we have been writing about till now.

When to use?

Since this is a creational design pattern, this is used when decision is to reduce the creation cost of object in a standard way. There can be argument about how this is then different from abstract factory pattern. The key benefit of Prototype design pattern is that it optimizes the use case where multiple objects of same type will have mostly same data.

Major example is reading configuration data from a file/database over a network. Also if you want to hide the logic of creating new instance from the client.

How to use?

Firstly, in this pattern, there is an interface of Prototype that has method for clone and any concrete class implementing this interface, implements the method to clone the object.

 

public interface Car {

Car clone();

}

We have an interface Car which we will implement in our concrete classes.

package com.bettterjavacode.designpatterns.prototypeexample;

public class Toyota implements Car 
{

    private final String CARNAME = "Toyota";

    public Car clone() 
    {
       return new Toyota();
    }

    @Override
    public String toString() 
    {
      return CARNAME;
    }

}

 

We will have a factory class that will get us a prototype based on type of object we have passed. This will look like below:

package com.bettterjavacode.designpatterns.prototypeexample;

import java.util.HashMap;
import java.util.Map;

public class CarFactory
{

   private static final Map<String, Car> prototypes = new HashMap<String, Car>();

   static 
   {
     prototypes.put("toyota", new Toyota());
     prototypes.put("lexus", new Lexus());
     prototypes.put("bmw", new BMW());
   }

   public static Car getPrototype(String type) 
   {
      return prototypes.get(type).clone();
   }
}

 

Therefore, our demo class will pass the type of car as an argument to print the carname. That will look like below:

package com.betterjavacode.designpatterns;

import com.bettterjavacode.designpatterns.prototypeexample.Car;
import com.bettterjavacode.designpatterns.prototypeexample.CarFactory;

public class PrototypeDemo 
{
   public static void main(String[] args) 
   {
      if (args.length > 0) 
      {
         for (String type : args) 
         {
            Car prototype = CarFactory.getPrototype(type);
            if (prototype != null) 
            {
               System.out.println(prototype);
            }
         }
      } 
      else 
      {
         System.out.println(" Run again with arguments");
      }
   }
}

Conclusion

In conclusion, we showed how to use prototype design pattern. The code for this is available here

References

  1. Design Patterns – Prototype
  2. Prototype Pattern

Design Patterns – Builder Pattern – Part V

Continuing the series of posts about design patterns, we will talk about builder pattern in this post. Builder pattern is of type creational design pattern. One of the major uses of Builder pattern is when there are too many constructor parameters to handle.

In my previous post, I showed how to use factory pattern.

When to use Builder Pattern?

Builder pattern enforces a step-by-step approach to create a complex object. The object can not be used till it’s a finished product. It helps to encapsulate complex creation logic. One of the examples from real time is file creation with a format. If you are creating a file in certain format (example xml, csv), you can use builder pattern to create a simple logical approach to creating the file.

How to use Builder Pattern?

Lately working on a project to build an EDI file to transfer between customer, I have to create a file of format 834. So 834 file format varies according to different health insurance carrier. This file format contains headers, records and trailers. Headers indicate different paradigm about the file and the customer and who is sending it. To show example of this pattern, I will use one of the headers of this file format and how it can be created using builder pattern.

One of the headers is called the Transactional Group Header. This header looks like below in a real file

ST*834*5432853*005010X220A1~

First field “ST” indicates that it is a transactional group. All the records for one customer can lie between ST and SE. 834 is a transaction code for file format. Since this is 834 file format, code is 834. 5432853 is a unique transaction control number, this can be anything between 4 digits in length to a maximum 9 digits in length. 005010X220A1 is an implementation reference number.

Our implementation of the class with have fields for each of these fields from a header, a private constructor and a static builder class. This is shown below:

public class TransactionalHeader implements Serializable {
private static final long serialVersionUID = 7517644545656169045L;

private String st;

private String transactioncode;

private String transactioncontrolnumber;

private String implementationreference;

public static class Builder {

private String st;

private String transactioncode;

private String transactioncontrolnumber;

private String implementationreference;

public Builder st(String st) {

this.st = st; return this;

}

public Builder transactioncode(String transactioncode) {

this.transactioncode = transactioncode; return this;

}

public Builder transactioncontrolnumber(String transactioncontrolnumber) {                            this.transactioncontrolnumber = transactioncontrolnumber; return this;

}

public Builder implementationreference(String implementationreference) {                                this.implementationreference = implementationreference; return this;

}

public TransactionalHeader build() {

return new TransactionalHeader(this);

}

}

private TransactionalHeader(Builder builder) {

this.st = builder.st;

this.transactioncode = builder.transactioncode;

this.transactioncontrolnumber = builder.transactioncontrolnumber;

this.implementationreference = builder.implementationreference;

}

public String toString() {

String result = "";

StringBuffer sb = new StringBuffer();

sb.append(st);

sb.append(FileUtil.FIELD_SPLITTER);

sb.append(transactioncode);

sb.append(FileUtil.FIELD_SPLITTER);

sb.append(transactioncontrolnumber);

sb.append(FileUtil.FIELD_SPLITTER);

sb.append(implementationreference);

sb.append("~");

result = sb.toString();

return result;

}

}

 

This was our builder class. Let’s create a demo class that will use this builder class to build an object that will give us a transactional header in the file. This will look like below:

public String getTransactionalHeader() {

String result = "";

TransactionalHeader th = new TransactionalHeader.Builder()

.st("ST")

.transactioncode(TRANSACTION_IDENTIFIER_CODE)

.transactioncontrolnumber(FileUtil.getTransactionControlNumber())

.implementationreference("005010X220A1").build();

result = th.toString();

return result;

}

 

Conclusion

In this way, we can use builder design patterns to construct complex objects. One of the easy ways to identify when to use this design pattern is when you have more than 4 or more parameters in your constructor.

The code for this post is available to download here.