Microservices in a minute

Microservices get more light in recent years as a new service oriented architecture with a high level of modularity. Compared to traditional web services either they are SOAP or REST, microservices are small in size and complexity but brings the cohesiveness to web services. Microservices do not require a servlet container or web server to be deployed instead they are created as individual JAR files which you can run as any other JAR files. The idea behind microservices is creating tiny individual services which can be developed, deployed and modified with less effort. This article introduces microservices using WSO2 Microservices Framework in a minute.

Microservices in a minute
Image Credits: http://wso2.com/blogs/thesource/2016/05/enabling-microservice-architecture-with-middleware/

WSO2 Microservices Framework for Java (WSO2 MSF4J) is a lightweight annotation based model to develop microservices in Java. Developers can create a microservice using just two or three classes which of course require a framework to take care of the householding tasks. The MSF4J hides all the complexities of creating a web service and provide a decent API to develop microservices in minutes. Let's dirt your hands with microservices:


Requirements:
  • Java Development Kit 1.8
  • Apache Maven 3.x
  • Git
  • Postman
  • Eclipse IDE / Any Text Editors

Step 1:
Execute the following Maven command from whatever the directory you like to create a Hello World service.
mvn archetype:generate -DarchetypeGroupId=org.wso2.msf4j \
-DarchetypeArtifactId=msf4j-microservice -DarchetypeVersion=2.0.0 \
-DgroupId=com.javahelps -DartifactId=Hello-Service -Dversion=0.1-SNAPSHOT \
-Dpackage=com.javahelps.service -DserviceClass=HelloService

Instead, you can create a new Maven project in Eclipse, using the given archetypeArtifactId.

Step 2:
Once you have confirmed the properties configuration in the terminal, you should get the following project in your system.
.
├── pom.xml
└── src
    └── main
        └── java
            └── com
                └── javahelps
                    └── service
                        ├── Application.java
                        └── HelloService.java

Step 3:
Change the current directory of the terminal to Hello-Service and execute the following command to build the JAR file.
mvn package

Step 4:
Once the project is built, execute the following command to run the JAR file in other words to start your HelloService.
java -jar target/Hello-Service-0.1-SNAPSHOT.jar

Step 5:
Open the Postman and try to send GET, POST, PUT and DELETE requests to the following endpoint.
Microservice in a minute

After every request, don't forget to check the output printed in the terminal which is running the microservice.

Yahoo! we have developed our first microservice. Whats next? executing Maven commands does not mean that you have learned something new. Let's analyse the source code.

Open the Hello-Service directory in your favorite editor or IDE.
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.wso2.msf4j</groupId>
        <artifactId>msf4j-service</artifactId>
        <version>2.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.javahelps</groupId>
    <artifactId>Hello-Service</artifactId>
    <version>0.1-SNAPSHOT</version>
    <name>WSO2 MSF4J Microservice</name>

    <properties>
        <microservice.mainClass>com.javahelps.service.Application</microservice.mainClass>
    </properties>

</project>
The pom.xml defines this project as a msf4j-service and declares the main class to execute using the microservice.mainClass property.

package com.javahelps.service;

import org.wso2.msf4j.MicroservicesRunner;

public class Application {
    public static void main(String[] args) {
        new MicroservicesRunner()
                .deploy(new HelloService())
                .start();
    }
}

The Application class which is the main class defined in pom.xml is a regular Java class with the main method creates a MicroservicesRunner object and deploys an instance of the HelloService class.

package com.javahelps.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@Path("/service")
public class HelloService {
    @GET
    @Path("/")
    public String get() {
        // TODO: Implementation for HTTP GET request
        System.out.println("GET invoked");
        return "Hello from WSO2 MSF4J";
    }
    @POST
    @Path("/")
    public void post() {
        // TODO: Implementation for HTTP POST request
        System.out.println("POST invoked");
    }
    @PUT
    @Path("/")
    public void put() {
        // TODO: Implementation for HTTP PUT request
        System.out.println("PUT invoked");
    }
    @DELETE
    @Path("/")
    public void delete() {
        // TODO: Implementation for HTTP DELETE request
        System.out.println("DELETE invoked");
    }
}

HelloService class contains the actual web service methods where the class and the methods are decorated using javax annotations. I hope the annotations are pretty straight forward and self-explanatory. The Path annotation defines the URL and other annotations used in this class are for the HTTP methods meant by their names. You can modify these methods as per your requirement and rerun the Application class.

Let me show you how to change the POST method to accept a POJO object as JSON and returns another POJO object as response.

Step 6:
Create a Student class in the existing package as given below.
package com.javahelps.service;

public class Student {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}

Step 7:
Modify the POST method according to the code provided below. Notice that there are two annotations @Consumes and @Produces defines the input and output media type. According to those definitions, now the method accepts a Student object as the parameter and returns a Student object. For simplicity, this method just converts the name to uppercase and returns the same student.
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Student post(Student student) {

  student.setName(student.getName().toUpperCase());
  return student;
}

After the modification, the HelloService class should look like this:
package com.javahelps.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/service")
public class HelloService {

  @GET
  @Path("/")
  public String get() {
    // TODO: Implementation for HTTP GET request
    System.out.println("GET invoked");
    return "Hello from WSO2 MSF4J";
  }

  @POST
  @Path("/")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Student post(Student student) {

    student.setName(student.getName().toUpperCase());
    return student;
  }

  @PUT
  @Path("/")
  public void put() {
    // TODO: Implementation for HTTP PUT request
    System.out.println("PUT invoked");
  }

  @DELETE
  @Path("/")
  public void delete() {
    // TODO: Implementation for HTTP DELETE request
    System.out.println("DELETE invoked");
  }
}

Step 8:
Save all changes, run the Application.java class and send POST request to the method with a JSON student object.

Microservice in a minute

In response, you should get the same Student object with the name converted into uppercase.

As you may wonder, my recent articles are mostly explaining WSO2 products. Of course, this tutorial uses the WSO2 MSF4J, but there are other vendors providing Microservices frameworks. For example, Sprint Boot, Restlet, Eclipse Vert.x, and even more frameworks are available to make your task easier. However, WSO2 MSF4J GitHub page claims that MSF4J framework provides comparatively better performance than most of the other frameworks. Please visit their GitHub page for more details: https://github.com/wso2/msf4j

If you have any questions regarding this article, feel free to comment below.

Find the project @ GitHub.

Previous
Next Post »

Contact Form

Name

Email *

Message *