Introduction to Light 4J Microservices Framework





2972

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Why Light 4J?

To start a Rest API microservices application it just takes milliseconds when compared to other microservices like spring boot (takes around 8 seconds). Detailed benchmark available here.



Spring Boot Startup Log

class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@4eabe900]

2019-02-28 20:53:05.109 INFO 10004 --- [ main] c.s.tutorial.controller.Application : Started Application in 8.299 seconds (JVM running for 9.175)





It can serve upto 3 million requests per second on commodity hardware with lesser memory footprint compared to typical java ee platform. Thereby reducing production operation cost.

All microservices cross cutting concerns like auditing, security, cluster support, logging and registry discovery are pre-built in to the framework which can be added on demand by configuring the scaffold project.

Architecture & Design

Principal of microservices is to break down the entire framework into smaller pieces, so customization and replacement will be done as necessary. Light 4J also uses the same microservice principal and have plugins implemented for different phases like route, middleware, startup, shutdown hooks. All the plugins are wired in request/response chain for best performance.

All the handlers are registered to the undertow http server based on composition / aggregation based architecture. It has built in OAuth2 security feature with maximum security and flexibilty.

Cloud native applications requires safe and reliable delivery of messages between microservice to another services. Communication between services can be done by dedicated infrastructure layer called service mesh. Light4j has light-eventuate-4j which manages the complexity of services by techniques like latency aware load balancing, eventual consistency, service discovery, retries, distributed transaction and deadlines. Transaction management done by JTA couldn't scale much because of synchronous communication and chance of partial failures. So event based framework(light-eventuate-4j) will provide eventual consistency.

In Distributed environment, logging will be complex which can be managed by centralized logging with tracing and correlation feature. It can be configured to open source ELK stack, where logs will be collected by Logstash, indexed by Elastic search and visually shown by Kibana reporting tool.

To read more about features in terms of design and architecture refer to Light 4J documentation.

Let's see the steps to start Rest service and enable security in it.

Setup and Start Rest Service

Light 4J works by design first approach, where developers work on only functional design and all non functional requirements provided by the framework. Framework has scaffolding code generation project which generates the basic Light 4J Rest project.

So let's clone the scaffolding code generation tool like below.

mkdir networknt

cd networknt

git clone https://github.com/networknt/light-codegen.git





Then the configuration project for code generation tool can be downloaded



git clone https://github.com/networknt/model-config.git





Now build the code generation tool through maven to generate Light 4J cli tool.

cd ~/networknt/light-codegen

mvn install -DskipTests





Then execute the cli tool and it generates sample PetStore REST API project based on OpenAPI3.0 specification. Generated project has configuration file for stage of the request-response chain.

cd ~/networknt

java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f openAPI -o light-example-4j/Rest/openAPI/petstore -m model-config/Rest/openAPI/petstore/1.0.0/openAPI.json -c model-config/Rest/openAPI/petstore/1.0.0/config.json



Passed parameter details:



-f - Whether it is OpenAPI 3.0 specification or swagger?

-o - Project target directory.

-m - IDL spec where each Rest API is defined with request and response format

-c - config file to provide package, project name and other details



Now execute the project to access the Rest API. It starts the server as https at port 8443

cd ~/networknt/light-example-4j/Rest/openAPI/petstore

mvn install exec:exec

Test whether Rest service is up with following url

https://127.0.0.1:8443/v1/pets



/*which will print all the pets */



[{"id":1,"name":"catten","tag":"cat"},{"id":2,"name":"doggy","tag":"dog"}]





We can also access single pet with "https://127.0.0.1:8443/v1/pets/1". If it is not accesible, just modify the ip address "ip: 127.0.0.1" in server.yml file available in petstore project.

Enable JWT

By default, the generated API has security turned off. Turn on the JWT verification by updating src/main/resources/config/openAPI-security.yml in petstore project as below.

# Enable JWT verification flag.

enableVerifyJwt: true



# If OAuth2 provider support http2 protocol. If using light-oauth2, set this to true.

oauthHttp2Support: true





Then restart the server for the configuration to take effect.

mvn clean install exec:exec



Now if we try the same url in browser [https://127.0.0.1:8443/v1/pets], the following exception will be shown

{

"statusCode":401,

"code":"ERR10002",

"message":"MISSING_AUTH_TOKEN",

"description":"No Authorization header or the token is not bearer type",

"severity":"ERROR"

}





So we need to access the Rest API with bearer JWT token in header which is available in readme.md. Then the list of pets will be displayed. To check on logs, check target/test.log file in petstore project folder.

Authorization: Bearer <<token>>



Create Hello World Rest API

Now lets try to create a sample Rest API in the generated petstore project. First we need to create a handler, which gets the name from the url and print in the string template. This handler will be present in the petstore project inside the source folder under the package com.networknt.petstore.handler.

package com.networknt.petstore.handler;



import com.networknt.handler.LightHttpHandler;

import io.undertow.server.HttpServerExchange;

import io.undertow.util.HttpString;



public class HelloWorldHandler implements LightHttpHandler {



@Override

public void handleRequest(HttpServerExchange exchange) throws Exception {

System.out.println(exchange.getQueryParameters().get("name"));

String name = exchange.getQueryParameters().get("name").peek();

System.out.println(exchange.getQueryString());

exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/text");

exchange.getResponseSender().send("hello " + name + "! welcome to Light 4J!!!");

}

}





Then we need to map the handler to the Rest API url with http method. This configuration needs to be done in handler.yml file which is present in src/main/resources/config folder.

- path: 'v1/pets/helloworld'

method: 'GET'

exec:

- default

- com.networknt.petstore.handler.HelloWorldHandler

Handler should also be added to the list of business handlers in the same file as shown below.



# Business Handlers

- com.networknt.petstore.handler.PetsGetHandler

- com.networknt.petstore.handler.HelloWorldHandler

- com.networknt.petstore.handler.PetsPostHandler

- com.networknt.petstore.handler.PetsPetIdGetHandler

- com.networknt.petstore.handler.PetsPetIdDeleteHandler

Now using Postman or Curl, Hit the following URL with get request. Add authorization header, if JWT token is enabled.

https://127.0.0.1:8443/v1/pets/helloworld?name=nagappan

Output as shown below will appear as response.

hello nagappan! welcome to Light 4J!!!

References:

https://github.com/networknt/light-4j