Java

What is Microservice and what exactly does it do?

Introduction

Understanding Micro service requires you to have a bit of knowledge about MVC or Monolithic Architecture which are very tightly coupled that to even make a normal change you need to deal up with a lot of processes and an update in any other part of the module can bring down your whole application down

Micro Service as per microservices.io

Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are

  1. Highly maintainable and testable
  2. Loosely coupled
  3. Independently deployable
  4. Organized around business capabilities
  5. Owned by a small team

With Micro Service we can achieve a very high level of atomicity that going down of one service won't affect the another. On contrary in case of a failure we can scale up the operations so well that when one particular service is getting more attention we can just increase the resources on that , so it is always High Available.

We are going to develop a Temperature Conversion API and convert it into a Micro Service and make two copies of the same micro service run at the same time.

API vs Microservice

API is a contract which makes the client aware of the underlying service whereas on other hand a microservice is an architectural design that separates portions of a (usually monolithic) application into small, self-containing services.

Let's Begin with the Code for the Project.

Step 1 is quite simple

ALT HACKED TYBCA

Go to https://start.spring.io/

 

Create a new project with below displayed dependencies.

 

Once you download the zip file. Go to your STS - Spring Tool Suite, It is an extension of Eclipse (You can download STS from here). Go To File and Import and Select Maven and Existing Maven Project. Unzip the downloaded file and select the Root Folder of your project, it will load up the project in STS / Eclipse

Select Maven

 

Once the project is loaded, it will take a bit of time to settle itself and you then once launched you can see the project structure like

Your job here to run the the main file. But before looking it up let see how pom.xml looks like

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  https://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <parent>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-parent</artifactId>
             <version>2.3.0.RELEASE</version>
             <relativePath/> <!-- lookup parent from repository -->
       </parent>
       <groupId>com.codewithz</groupId>
       <artifactId>spring-cloud-config</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <name>spring-cloud-config</name>
       <description>Spring Cloud Config Server</description>
       <properties>
             <java.version>1.8</java.version>
             <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
       </properties>
       <dependencies>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
             </dependency>
             <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-config-server</artifactId>
             </dependency>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-test</artifactId>
                    <scope>test</scope>
                    <exclusions>
                          <exclusion>
                                 <groupId>org.junit.vintage</groupId>
                                 <artifactId>junit-vintage-engine</artifactId>
                          </exclusion>
                    </exclusions>
             </dependency>
       </dependencies>
       <dependencyManagement>
             <dependencies>
                    <dependency>
                          <groupId>org.springframework.cloud</groupId>
                          <artifactId>spring-cloud-dependencies</artifactId>
                          <version>${spring-cloud.version}</version>
                          <type>pom</type>
                          <scope>import</scope>
                    </dependency>
             </dependencies>
       </dependencyManagement>
       <build>
             <plugins>
                    <plugin>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
             </plugins>
       </build>
</project>

Also you need to go in resources> application.properties and set the port to 8888 as a standard practice.

application.properties

server.port=8888

Finally the main class looks like

SpringCloudConfigApplication.java

package com.codewithz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication

public class SpringCloudConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudConfigApplication.class, args);
    }
}

Once done, right click on the file and Run as> Spring Boot Project

Once it starts , now is the time for Step 2

Do the same process again

Repeat the same procedure to unzip the folder and import as Maven Project, once done let's set the port to 7000 as I did as in my case port 8080 was used by some other service.

You can go to application.properties of the new project and set the port to 7000

 

application.properties

server.port=7000

My pom.xml for this project looks like ( You need not worry about pom.xl much if you have used the right dependencies but it is always handy to know about it)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  https://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <parent>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-parent</artifactId>
             <version>2.3.0.RELEASE</version>
             <relativePath/> <!-- lookup parent from repository -->
       </parent>
       <groupId>com.codewithz</groupId>
       <artifactId>TemperatureMicroservice</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <name>TemperatureMicroservice</name>
       <description>Microservice App</description>
       <properties>
             <java.version>1.8</java.version>
             <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
       </properties>
       <dependencies>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-actuator</artifactId>
             </dependency>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
             </dependency>
             <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-config</artifactId>
             </dependency>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <scope>runtime</scope>
                    <optional>true</optional>
             </dependency>
             <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-test</artifactId>
                    <scope>test</scope>
                    <exclusions>
                          <exclusion>
                                 <groupId>org.junit.vintage</groupId>
                                 <artifactId>junit-vintage-engine</artifactId>
                          </exclusion>
                    </exclusions>
             </dependency>
       </dependencies>
       <dependencyManagement>
             <dependencies>
                    <dependency>
                          <groupId>org.springframework.cloud</groupId>
                          <artifactId>spring-cloud-dependencies</artifactId>
                          <version>${spring-cloud.version}</version>
                          <type>pom</type>
                          <scope>import</scope>
                    </dependency>
             </dependencies>
       </dependencyManagement>
       <build>
             <plugins>
                    <plugin>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
             </plugins>
       </build>
</project>

Now we will create our API under the package of controller and return a Bean from there. Following is the code

Create a package by name model inside com.codewithz and make a new Java file

TemperatureBean.java

package com.codewithz.model;
public class TemperatureBean
{
       
       Long id;
       
       String from;
       
       String to;
       
       double temperature;
       
       double convertedValue;
       public TemperatureBean(Long id, String from, String to, double  temperature)
       {
             super();
             this.id = id;
             this.from = from;
             this.to = to;
             this.temperature = temperature;
             
             if(from.contentEquals("DEG") && to.contentEquals("FH"))
             {
                    this.convertedValue=convertFromDegToFH(temperature);
             }
             if(from.contentEquals("FH") && to.contentEquals("DEG"))
             {
             this.convertedValue=convertFromFHToDeg(temperature);
             }
           
       }
       public Long getId() {
             return id;
       }
       public void setId(Long id) {
             this.id = id;
       }
       public String getFrom() {
             return from;
       }
       public void setFrom(String from) {
             this.from = from;
       }
       public String getTo() {
             return to;
       }
       public void setTo(String to) {
             this.to = to;
       }
       public double getTemperature() {
             return temperature;
       }
       public void setTemperature(double temperature) {
             this.temperature = temperature;
       }
       public double getConvertedValue() {
             return convertedValue;
       }
       public void setConvertedValue(double convertedValue) {
             this.convertedValue = convertedValue;
       }
       public TemperatureBean() {
       
       }
       
       public double convertFromDegToFH(double degree)
       {
             System.out.println("DegreeToFH Invoked");
             double fh=(((9 * degree)+(32*5))/5);
             return fh;
       }
       
       public double convertFromFHToDeg(double fh)
       {
             System.out.println("FHToDegree Invoked");
             double degree=(( 5 *(fh - 32.0)) / 9.0);
             return degree;
       }
              
}

Now create a new package within com.codewithz by name controller and write the following class

TemperatureController.java

package com.codewithz.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.zartab.ruia.test.model.TemperatureBean;
@RestController
public class TemperatureController
{
       @GetMapping("/convert/from/{from}/to/{to}/temperature/{temperature}")
       public TemperatureBean convertFromDegreeToFahreniet(@PathVariable String  from,@PathVariable String to,@PathVariable String temperature)
       {
             double temp=Double.parseDouble(temperature);
             
             TemperatureBean bean=new TemperatureBean(1L,from,to,temp);
             
             return bean;
             
       }
       @GetMapping("/")
       public String sayHello()
       {
             return "Hello World!!";
       }
}

and finally go to the main class which looks like

TemperatureMicroserviceApplication.java

package com.codewithz;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class TemperatureMicroserviceApplication {


    public static void main(String[] args) {
        SpringApplication.run(TemperatureMicroserviceApplication.class, args);
    }


}

Once done, right click on the file above and repeat the same process for Run As Spring Boot App.

You will see following message in Console

 

And you can access it from your browser in following way

Now my main job is to scale this microservice which is running on port 7000 to also run on 7001 so that I can balance the load in case of increased requests

 

So to do that, while the service is now running , click on the Run Button on top and select Run Configurations

Find your service on the screen and duplicate the service

Once Duplicated, give it a name in my case I have attached port numner 7001 as a suffix and I am adding arguments to the same as

-Dserver.port=7001

this will override any settings of application.properties. Once done then select Apply and then Run, it will start the same process on port 7001

This will get your application running on port 7001 in addition to port 7000.

 

So this brings us to the end of this special post dedicated towards my fellow Ruiates. As discussed during the webinar, just drop an email if any help needed on zartab@codewithz.com with subject "Buddy from Ruia" and I will revert for sure.

Keep Hustling!!

 

Related Posts

Table Of Contents

;