Introduction to Light 4J Microservices Framework

  •        0
  

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.

Light4j handler chain

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

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a freelance developer and also does corporate training. He can be reached at nagappan08@gmail.com

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


Microsoft released F# under Open Source

  • fsharp opensource

F# is a functional programming language for the .NET Framework. It combines the succinct, expressive and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET. Microsoft recently released its source code under Apache License.

Read More



An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More


GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More


PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More


Struts 1.x End Of Life. Whats alternative?

  • java eol struts

The Apache Struts Project Team announced End of Life (EOL) for Struts 1.x web framework. Struts was launched in the year 2000. It is only of the widely used web framework. It gave better control over writing UI and business logic code directly in to JSPs.

Read More


How to create SEO friendly url

  • seo url searchengine

SEO friendly URL is recommended for any website which wants to be indexed and wants its presence in search results. Searchengine mostly index the static URL. It will avoid the URL which has lot of query strings. Almost all websites generate content dynamically then how could the URL be static. That is the job of the programmer.

Read More


MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

Read More


Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More


How to learn from open source projects

  • open-source learning methodology

Students ask this question frequently steps or methodology to learn from open source projects. There is no single answer or steps available. I listed the steps which i follow and i hope this will help for few.

Read More


Free Open Source Code Search Engines

  • code-search code-search-engine search-engine

There are couple of sites which indexes the open source code and provides support to search code. Recently Google announced that they removed code search support from Google code. This article provides pointer for code search engine sites.

Read More


An introduction to MongoDB

  • mongodb database document-oriented-databse no-sql c++ data-mining

MongoDB is the most exciting SQL-free database currently available in the market. The new kid on the block, called MongoDB is a scalable, high-performance, open source, schema free and document oriented database that focuses on the ideas of NoSQL Approach. Written in C++, it has taken rapid strides since its emergence into the public sphere as a popular way to build your database applications.

Read More


Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More