What Are Microservices In Java?

What Are Microservices In Java?
What Are Microservices In Java?

Introduction

We are living in a digital world where almost everything can be done online. The Internet makes it possible to quickly find information, communicate with people around the world, manage your finances, shop from home, listen to music, watch videos, and much, much more.

Amazon, one of the most popular online stores, uses Microservices in java to deliver products to customers decomposed by use case. Spotify uses decomposition by resources to manage the user’s account. So you might be wondering what decomposition by use case or resource means? Just hold onto these terms for a while and we shall discuss them. 

What are Microservices?

Microservices are small, autonomous programs that function as data producers and data consumers, particularly between service boundaries within a virtualized cloud environment. 100-200 individual microservices might be used to render a single Amazon web page. Microservices in Java are also used by Netflix, Uber web pages.

A microservice is a small, loosely coupled distributed service. Microservice Architectures evolved as a solution to Monolith architectures’ scalability and innovation challenges (Monolith applications are typically huge – more than 100, 1000 lines of code). It allows you to take a large application and decompose or break it into easily manageable small components with narrowly defined responsibilities.

Microservices in J- also known as the Microservice architecture – is an architectural style that structures an application as a collection of the following capabilities: 

  • Highly maintainable and testable
  • Loosely coupled 
  • Independently deployable
  • Organised around the business

Image Source: Medium

Microservice Architecture is a Service Oriented Architecture. By combining a larger number of microservices, a great service architecture is formed. Here all the services communicate with each other. The services have to follow a certain set of pre-defined rules, to maintain order. Let’s discuss them.

Principles of Microservices

The “must-have” principles of a microservice are:

  • Single Responsibility principle: The single responsibility principle states that a class should have a single reason to change. Any microservice cannot serve more than one responsibility at a time.
  • Modelled around the business domain: Microservices in java never restricts themselves from accepting appropriate technology stack or database. The stack or database is most suitable for solving the business purpose.
  • Isolate Failure: The large application can remain mostly unaffected by the failure of a single module. A service might fail at any time. So, it is important to detect failure quickly, if possible, automatically restore failure.
  • Infrastructure automation: Infrastructure automation is the process of scripting environments. With the help of a scripting environment, we can apply the same configuration to a single node or thousands of nodes. It is also known as configuration management, scripted infrastructures, and system configuration management.
  • Deploy independently: Microservices in Java are platform agnostic. It means we can design and deploy them independently without affecting the other services.

Benefits of Microservices in Java

We have a vast number of applications and benefits of Microservices which are the best practices, few are:

  • Smaller Modules: The application is broken into smaller modules that are easy for developers to code and maintain.
  • Easier Process Adaption: By using microservices in java, new Technology & Process adaption becomes easier. You can try new technologies with the latest microservices that we use.
  • Independent scaling: Each microservice can scale independently via X-axis scaling (cloning with more CPU or memory) and Z-axis scaling (sharding), based upon their requirements.
  • Unaffected: Large applications remain unaffected by the failure of a single module.
  • DURS: Each service can be independently DURS (deployed, updated, replaced, and scaled).

Restrictions of Microservices

  • Configuration Management: As it becomes granular, the headache comes from configuring the services and monitoring those. You need to maintain configurations for hundreds of components across environments.
  • Debugging: Tracking down the service failure is a meticulous job. You might need to look into multiple services across different components. Centralised Logging and Dashboards are essential to make it easy to debug problems.
  • Automation: As there are several smaller components instead of a monolith, you need to automate everything – Builds, Deployment, Monitoring, etc.
  • Testing: It needs a greater effort from end to end. In addition, you are testing, as it needs all the dependent services to be up and running.

So far, end-to-end, we have seen the benefits, principles, and restrictions of microservices. Let’s design some applications now.

Microservice frameworks in Java

Several microservices in java, frameworks can be used for deploying Java. Some of them are:

  • Spring Boot: This is probably the best microservices in the Java framework that works on top languages for Inversion of Control, Aspect-Oriented Programming, etc.
  • Drop wizard: Dropwizard pulls together stable, mature libraries from the Java ecosystem into a simple, lightweight package that lets you focus on getting things done.
  • Restlet: Restlet Framework helps Java developers build better web APIs that follow the REST architecture style.
  • Jersey: This open-source framework supports JAX-RS APIs in Java and is very easy to use.
  • Swagger: Helps you in documenting API and gives you a development portal, which allows users to test your APIs.
  • Spark: A micro-framework for creating web applications in Kotlin and Java 8 with minimal effort.

We also have many frameworks like Ninja Web Framework, Play Framework, RestExpress, etc.

How to create using Dropwizard?

DropWizard pulls together mature and stable Java libraries in lightweight packages that you can use for your applications. It uses Jetty for HTTP, Jersey for REST, and Jackson for JSON, along with Metrics, Guava, Logback, Hibernate Validator, Apache HttpClient, Liquibase, Mustache, Joda Time, and Freemarker.

You can also check the documentation here.

Let’s explore a sample code.

<properties>

<dropwizard.version>LATEST VERSION</dropwizard.version>

</properties>

Then list the dropwizard-core library:

<dependencies>

<dependency>

<groupId>io.dropwizard</groupId>

<artifactId>dropwizard-core</artifactId>

<version>${version}</version>

</dependency>

</dependencies>

The above code will set up a Maven project for you. From here, you can create a configuration class, an application class, a representation class, a resource class, or a health check, and you can also build Fat JARS and then run your application.

Microservices with Spring Boot

Spring Boot gives you a Java application to use with your apps via an embedded server. It uses Tomcat, so you do not have to use Java EE containers. A sample Spring Boot tutorial is at this link.

You can find the Spring Boot projects here, and you will realize that Spring Boot has all the infrastructures that your applications need.

Sample code:


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

The hello() method is designed to take a String parameter called name and then combine this parameter with the word “Hello” in the code. This means that if you set your name to “Amy” in the request, the response would be “Hello Amy.”

The @RestController annotation tells Spring that this code describes an endpoint that should be made available over the web. 

The @GetMapping(“/hello”) tells Spring to use the hello() method to answer requests that are sent to the http://localhost:8080/hello address. 

Finally, the @RequestParam is telling Spring to expect a name-value in the request, but it will use the word “World” by default if it’s not there.

You can try it on windows using the command: “mvnw spring-boot:run” and for Linux: “./mvnw spring-boot:run.”

You will get an image similar to this:

Jersey

Jersey RESTful framework is open source, and it is based on JAX-RS specification. Jersey’s applications can extend existing JAX-RS implementations and add features and utilities that would make RESTful services simpler and make client development easier.

The best thing about Jersey is its exceptional documentation. It’s filled with excellent examples. Jersey is also fast and has extremely easy routing.

A sample code that you can try:

package org.glassfish.jersey.examples.helloworld;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("helloworld")
public class HelloWorldResource {
    public static final String CLICHED_MESSAGE = "Hello World!";

 @GET
    @Produces("text/plain")
    public String getHello() {
        return CLICHED_MESSAGE;
    }
}

The above code prints a Hello World message. Jersey is very easy to use with other libraries, such as Netty or Grizzly, supporting asynchronous connections. It does not need servlet containers. It does, however, have an unpolished dependency injection implementation.

Play Framework

It gives you an easier way to build, create, and deploy Web applications using Scala and Java. This framework is ideal for a RESTful application that requires you to handle remote calls in parallel. It is also very modular and supports async. Play Framework also has one of the biggest communities out of all microservices frameworks.

Sample code you can try:


package controllers;
import play.mvc.*;
public class Application extends Controller {
    public static void index() {
        render();
    }

    public static void sayHello(String myName) {
        render(myName);
    }
}

Restlet

Restlet helps developers create fast and scalable Web APIs that adhere to the RESTful architecture pattern. It has good routing and filtering and is available for Java SE/EE, OSGi, Google AppEngine (part of Google Compute), Android, and other major platforms.

Restlet comes with a steep learning curve that is made worse by a closed community, but you can probably get help from people at StackOverflow.

Sample code:

package firstSteps;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/** 
 * Resource which has only one representation. 
 */
public class HelloWorldResource extends ServerResource {
    @Get
    public String represent() {
        return "hello, world";
    }
}

Frequently Asked Questions

What are Microservices in Java?

Microservices are a form of service-oriented architecture style (one of the most important skills for Java developers) wherein applications are built to collect different smaller services rather than one whole app.

Is Java good for Microservices?

Java is great for writing microservices. Among other reasons, its annotation syntax is easy to read. Java annotations make writing microservices much easier, especially when powered by a framework like Spring Boot. There’s a lot of value in readability, especially when it comes to working on complex systems.

Is spring boot a Microservice?

Spring Boot is an open-source framework based on the Java platform to create excellent microservices. It can help you build spring applications that can be used in the applications and are production-ready.

Is Docker a Microservice?

Since you have microservices architecture, you can now encapsulate each of them in Docker containers. Docker containers are lightweight, resource isolated environments through which you can build, maintain, ship, and deploy your application.

Key Takeaways

The article describes Microservices and the principles followed by their frameworks, benefits, and restrictions. Elaborating with some examples of microservices using different frameworks. Microservice architecture is quickly becoming a preferred way of building applications throughout industries.

It is a much more flexible and cheaper method of developing an application that can grow and evolve with its Monolith architecture requirements while delivering consistent customer service. 

By Dharani Mandla