How to Build Microservices in Java?
Decipher Zone Technologies Pvt Ltd
Custom Software Development Company
Now you will wish it could become more independently deployable, resilient, and scalable. If you want to do so, you need to think on the granular level, i.e., the application architecture that will lead you to microservices.
Microservices are not a new concept but have gained popularity when applications became more complex and distributed due to their loosely coupled architecture.
So in this article, we will be looking at the basics of microservices and how you can build microservices-based applications if your preferred programming language is Java.
What is Microservices Architecture?
Microservices Architecture (MSA) is an architectural approach to developing an application system that divides the domain model of the?business into small, bounded-text, and consistent services. The services in the MSA are autonomous and isolated from each other but can communicate through?APIs to process user requests. It enables frequent, reliable, and frequent delivery of complex applications.
Microservices are usually operated and implemented by small teams, meaning the team has enough autonomy to change the service or replace it with little or no impact on the entire system. Each team will have to design the service with their choice of the?technology stack?for solving an issue, deploying, and handling it
Using Microservices architecture, a developer can:
How to build Microservices in Java?
Building Microservices in Java??When it comes to the development of the microservices application, choosing the right language is a must. Hence, using?Java?and its frameworks like?DropWizard, SpringBoot, and WildlySwarm to build a microservices-based application can prove to be a great choice. The strength of building Microservices in Java is that it enables developers to analyze other frameworks and languages without adhering to higher risks via its virtual machine.?Java Virtual Machine?(JVM) is a remarkable platform that offers developers a chance to use different languages abroad.
We can build microservices with these Java frameworks:
Its comprehensive configuration and programming model make it easy to create stand-alone microservice applications. Some of the features that if included are dependency injection, i18n, data binding, events, validation, resources, type conversion, Aspect-Oriented Programming (AOP), testing through mock objects, Spring MVC test, TestContext framework, integrations such as Java Management Extensions (JME),?Java Message Service?(JVM), Java EE Connector Architecture (JCA), cache, etc. It is one of the best frameworks that work on top of programming languages for Inversion of Control.
DropWizard:
It straddles the line between framework and library. It is used to develop high-performing, reliable implementations of everything that might be needed in the development of the?web application. As the developed functionality is extracted into a reusable library, the application you are working on remains focused and lean reducing maintenance load and time-to-market. It also supports JAX-RS APIs making it easy to access web resources.
Wildfly Swarm:
It is a Java framework based on the Wildfly?Java app server. Wildfly swarm allows developers to create small, independent, standalone microservice applications. It is capable of creating just enough app-servers to support different applications’ components. An unbounded set of capabilities, each referred to as a fraction, defines it. These fractions have access to APIs like CDI or JAX-RS.
Now that we know what Microservices in?Java?is as well as the frameworks that can be used to build microservices apps, it is time to know how it can be built using these frameworks.
So let’s move on to the next section.
SpringBoot for Microservices
SpringBoot is also an opinionated framework that we can use for developing microservices. With SpringBoot you can create microservices according to Spring Dependency Injection through reduced configuration, boilerplate, and developer friction.
SpringBoot does this by favoring default conventional configuration, simplifying the application packaging, curating dependencies set for easier consumption, and getting application insights from metrics and environment data.
Once Spring was a nightmare when it came to the configuration as it required a deep understanding of beans and a lot of XML to build JmsTemplates, servlet listeners,?JDBCTemplates, and more. Now SpringBoot focuses on eliminating such configuration boilerplates with some simplified annotations and implied conventions.
It offers a large set of curated libraries that allows you to add things like?NoSQL databases, JPA persistence, Redis caching, JTA transactions, and Tomcat/Undertow/Jetty servlet engine.
Additionally, SpringBoot uses a first-class loader JAR to package all dependencies and application code. This makes it easier to understand dependent ordering, application startup, and log statements while reducing the number of steps one needs to take to securely move an app to production. It means that you don’t have to take the entire app and transfer it to the app server at once. Now a simple java -jar is enough to start the application.
Remember that all these functions are not only followed in SpringBoot but also in DropWizard and Wildfly Swarm.
To get started with SpringBoot we are going to use its command-line interface and bootstrap the first SpringBoot application. You can also use Spring Initializr plug-ins for the IDE you prefer.
Once you have installed?Command Line Interface?(CLI) tool according to your development environment, you can check the Spring version from
$ spring --version
Spring?CLI?v1.3.3.RELEASE
Now navigate to the directory to host the application and run the command given as below:
spring?init?--build?maven?--groupId?com.redhat.examples
--version?1.0?--java-version?1.8?--dependencies?web
--name?hola-springboot?hola-springboot
From this command, a directory named hola-springboot along with a complete Spring Boot application will be created.
Now if you will navigate to the hola-springboot directory then run the following code:
$ mvn spring-boot:run
If?everything is working as expected, you will see logging like:
2016-03-25 10:57:08.920 [main] AnnotationMBeanExporter
: Registering beans?for?JMX exposure on startup
2016-03-25 10:57:08.982 [main] TomcatEmbeddedServletContainer
: Tomcat started on port(s): 8080 (http)
2016-03-25 10:57:08.987 [main] HolaSpringbootApplication
: Started HolaSpringbootApplication?in?1.0 seconds
(JVM running?for?4.7)
If you will run this application in the local host of your browser, you will see an error page stating the application has no explicit mapping, which is expected as the app doesn’t do anything yet.
So you can create a simple Hello program, add Rest &?HTTP?endpoints, externalize configuration, expose application metrics, run the application outside Maven and call another service.
To know more about SpringBoot use cases and examples you can check its?reference guide?and?GitHub.
DropWizard for Microservices
DropWizard was developed before Wildfly Swarm or SpringBoot by Coda Hale at Yammer. The core aim of DropWizard was to empower the company’s distributed architecture (microservices), leveraging Java Virtual Machine (JVM). It is an opinionated framework when it comes to “just get to writing code” with a little perspective. It consists of some components that cannot be changed easily and come with a dependency-injection container that you can add later on. It prefers to bundle entire system components into one executable uber JAR so you don’t have to worry about deploying and configuring application servers required to run.
DropWizard also provides intuitive abstractions on top of the following libraries to make it easier to write the microservices application.
DropWizard exposes the below-mentioned abstractions. If you have a clear understanding of these, you can be highly productive while working with DropWizard.
To get started with DropWizard you don’t need any fancy initialization helpers or plug-ins. You can use JBoss Forge (tech-agnostic Java Coordination & Management tool) to quickly create projects, and add classes and dependencies.
All you need to do is choose a library you want to create your DropWizard project in, install the Maven archetype, and verify the Maven. Run the following command from the command prompt of your system:
$ mvn -B archetype:generate -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-simple -DarchetypeVersion=0.9.2 -DgroupId=com.redhat.examples.dropwizard -DartifactId=hola-dropwizard -Dversion=1.0 -Dname=HolaDropwizard
Navigate the directory created by Maven archetype generator in the hola-dropwizard directory and run the following command:
$?mvn clean install
This will create a successful build. It uses the DropWizard archetype java-simple to create a microservice.
Remember that DropWizard creates a package structure for API, CLI, Client,?Database,?Health, and resources that follows their conventions. We also have the files Hola-DropWizardCofiguration.java and Hola-DropWizardApplication.java, where the?bootstrapping?and configuration code will go.
Once you have created the basic template, you will have to add REST endpoints, and HTTP endpoints, externalize configuration, and expose metrics and information about the application.
You can also check some examples of DropWizard from?GitHub.
Wildfly Swarm for Microservices
Wildfly Swarm is a relatively new Java framework in comparison with SpringBoot and DropWizard. Wildfly Swarm uses the JBoss Wildfly?application server’s tried-and-tested Java EE functionality. It is a complete breakdown of the Wildfly application server into reusable components that can be blended into a microservice application.
Although deploying and managing applications in the Java EE environment is unsuitable for microservices architectures, the APIs, component models, and libraries that are available in Java EE for developers prove to be exceptionally useful.
WildFly Swarm assesses the pom.xml file and decides the Java EE dependencies that can be used in your microservice to create uber JAR including minimal Java EE implementations and APIs to run the services. This process is popularly known as “just enough application server” where you can use some useful Java EE APIs and deploy them in both traditional and microservices ways.
To get started with Wildfly Swarm you have three ways:
You can also add minimal dependencies and plug-ins to create a Vanilla Java project to complete.
领英推荐
To get up and running with Wildfly Swarm, you can add the following code to your pom.xml in your preferred?IDE. But first, it is important to build uber?JAR?that will determine the essential Java EE API functionality to run the app. So we will add the Wildfly Swarm Maven plug-in to pom.xml:
<plugins>
<plugin>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-plugin</artifactId>
<version>${version.wildfly.swarm}</version>
<executions>
<execution>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
And to add Wildfly Swarm Bill of Material (BOM) as a dependency and sort out the proper versions of all fractions and APIs, write the following code:
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs
including a Bill of Materials (BOM). A BOM specifies
the versions of a "stack" (or a collection) of
artifacts. We use this here so that we always get
the correct versions of artifacts. -->
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>bom</artifactId>
<version>${version.wildfly.swarm}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Now we will install JBoss Forge, a set of CLI and IDE plugins for Java Projects, that has plug-ins for Eclipse, NetBeans, and Intellij that help you to add CDI Beans, servlets, and JPA entities.
You will be able to start the CLI once it has been installed:
$?forge
It will allow you to explore commands by pressing Tab and gives command auto-completion.
To add Wildfly Swarm addon in JBoss Forge, write:
[temp]$?addon-install
--coordinate?org.jboss.forge.addon:wildfly-swarm,1.0.0.Beta2
***SUCCESS***?Addon org.jboss.forge.addon:wildfly-swarm,
1.0.0.Beta2?was?installed?successfully.
Now to build Java EE project in Wildfly Swarm, you can create a project-new command as follows:
[swarm]$ project-new
***INFO*** Required inputs not satisfied, interactive?mode
* Project name: hola-wildflyswarm
? Package [org.hola.wildflyswarm]:?com.redhat.examples.wfswarm
? Version [1.0.0-SNAPSHOT]: 1.0
? Final name: hola-wildflyswarm
? Project location [/Users/ceposta/temp/swarm]:
[0] (x) war
[1] ( ) jar
[2] ( ) parent
[3] ( ) forge-addon
[4] ( ) resource-jar
[5] ( ) ear
[6] ( ) from-archetype
[7] ( ) generic
Press <ENTER>?to?confirm, or <CTRL>+C?to?cancel.
* Project type: [0-7]
[0] (x) Maven
Press <ENTER>?to?confirm, or <CTRL>+C?to?cancel.
* Build system: [0]
[0] ( ) JAVA_EE_7
[1] ( ) JAVA_EE_6
[2] ( ) NONE
Press <ENTER>?to?confirm, or <CTRL>+C?to?cancel.
? Stack (the technology stack that the project will use): [0-2] 2
***SUCCESS*** Project named 'hola-wildflyswarm'
has been created.
So we have a blank Java project. This section describes how to configure JAX-RS and Wildfly Swarm for things like BOM management and the Maven plugin. Then you can build and run a new Wildfly Swarm microservice application.
Similar to SpringBoot and DropWizard applications that were based on microservices, you can create a simple Hello World program, add HTML endpoints, externalize configuration, expose metrics of application, learn how to run it outside maven, and start creating and calling other services.
To know more about Wildfly Swarm, you can check Wildfly Swarm?documentation?and?GitHub core examples.
Conclusion
Microservices in Java are much more extensive than we have shared in this blog. But we hope this blog has helped to understand the basic steps and information required to build a microservice architecture-based application using Java and some of its frameworks. As a programmer, you can also try and build a basic app by yourself.
However, if you are a medium to a large-scale businessman who wants to develop a microservices-based application, then?hire developers?from trustworthy?java Development companies?like Decipher Zone Technologies.