What are Microservices? Code Examples, Best Practices, Tutorials and More

By: Alexandra
  |  December 12, 2023
What are Microservices? Code Examples, Best Practices, Tutorials and More

Microservices are increasingly used in the development world as developers work to create larger, more complex applications that are better developed and managed as a combination of smaller services that work cohesively together for more extensive, application-wide functionality.

Tools such as Service Fabric are rising to meet the need to think about and build apps using a piece-by-piece methodology that is, frankly, less mind-boggling than considering the whole of the application at once.

Today, we’ll take a look at microservices, the benefits of using this capability, and a few code examples.

What are Microservices?

Microservices are an architectural style that develops a single application as a set of small services. Each service runs in its own process. The services communicate with clients, and often each other, using lightweight protocols, often over messaging or HTTP.

Microservices can be thought of as a form of service-oriented architecture (one of the most critical skills for Java developers) wherein applications are built as a collection of different smaller services rather than one whole app.

Instead of a monolithic app, you have several independent applications that can run on their own. You can create them using different programming languages and even different platforms. You can structure big and complicated applications with simpler and independent programs that execute by themselves. These smaller programs are grouped to deliver all the functionalities of the big, monolithic app.

Microservices captures your business scenario, answering the question, “What problem are you trying to solve?”

Instead of large teams working on large, monolithic projects, smaller, more agile teams develop the services using the tools and frameworks they are most comfortable with. Each of the involved programs is independently versioned, executed, and scaled. These microservices can interact with other microservices and can have unique URLs or names while being always available and consistent even when failures are experienced.

What are the Benefits of Microservices?

There are many benefits to using microservices. Some of them are related to how they allow your developers to write code. Other influence your architecture.

Microservices are small applications that your development teams create independently. Since they communicate via messaging if at all, they’re not dependent on the same coding language. Developers can use the programming language that they’re most familiar with. This helps them come work faster, with lower costs and fewer bugs

Since your teams are working on smaller applications and more focused problem domains, their projects tend to be more agile, too. They can iterate faster, address new features on a shorter schedule, and turn around bug fixes almost immediately. They often find more opportunities to reuse code, also.

Microservices improve your architecture’s scalability, too.

With monolithic systems, you usually end up “throwing more hardware” at the problem or purchasing expense and difficult-to-maintain enterprise software. With microservices, you can scale horizontally with standard solutions like load balancers and messaging.

Also, as more and more enterprises embrace the cloud, you’re probably looking that way, too. Microservices are a great way to get there.

Cloud platforms lend themselves to newer technologies like containerization. Microservices lend themselves to containerization too, since they already are small applications with a limited set of dependencies. This means you can scale your services horizontally with technologies like Docker and Kubernetes without writing any customized code.

Examples of Microservices Frameworks for Java

There are several microservices frameworks that you can use for developing for Java. Some of these are:

  • Spring Boot. This is probably the best Java microservices framework that works on top of languages for Inversion of Control, Aspect-Oriented Programming, and others.
  • Jersey. This open-source framework supports JAX-RS APIs in Java and is very easy to use.
  • Swagger. Helps you document API as well as gives you a development portal, which allows users to test your APIs.
  • Quarkus. This is a lightweight Java framework optimized for GraalVM and HotSpot, and it’s tightly integrated with Kubernetes.
  • Micronaut. It’s based on the Netty framework, which makes it well-suited for microservices that need to handle a lot of traffic.
  • Helidon. A microservices framework developed by Oracle. It is based on the MicroProfile specification, making it interoperable with other MicroProfile-based frameworks.
  • AxonIQ. A microservices framework designed for event-driven architectures. It provides a comprehensive toolkit for building event-driven microservices, including a message bus, event sourcing, and CQRS.

Others that you can consider include: Dropwizard, Ninja Web Framework, Play Framework, RestExpress, Restlet, Restx, and Spark Framework.

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 setup a Dropwizard application using Maven. How?

In your POM, add in a dropwizard.version property using the latest version of DropWizard.

<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>

This 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, then run your application.

Check out the Dropwizard documentation at this link. The Github library is here.

Sample code:

package com.example.helloworld;
import com.yammer.dropwizard.config.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
public class HelloWorldConfiguration extends Configuration {
@NotEmpty
@JsonProperty
private String template;
@NotEmpty
@JsonProperty
private String defaultName = "Stranger";
public String getTemplate() {
return template;
}
public String getDefaultName() {
return defaultName;
}
}

Microservices with Spring Boot

Spring Boot gives you Java application to use with your own 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 all Spring Boot projects here, and you will realize that Spring Boot has all the infrastructures that your applications need.

It doesn’t matter if you are writing apps for security, configuration, or big data; there is a Spring Boot project for it.

Spring Boot projects include:

  • IO Platform: Enterprise-grade distribution for versioned applications.
  • Framework: For transaction management, dependency injection, data access, messaging, and web apps.
  • Cloud: For distributed systems and used for building or deploying your microservices.
  • Data: For microservices that are related to data access, be it map-reduce, relational, or non-relational.
  • Batch: For high levels of batch operations.
  • Security: For authorization and authentication support.
  • REST Docs: For documenting RESTful services.
  • Social: For connecting to social media APIs.
  • Mobile: For mobile Web apps.

Sample code:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}

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, as well as making 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.

The documentation on how to get started with Jersey is at this link, while more documentation can be found here.

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;
}
}

Jersey is very easy to use with other libraries, such as Netty or Grizzly, and it supports asynchronous connections. It does not need servlet containers. It does, however, have an unpolished dependency injection implementation.

Play Framework

Play Framework gives you an easier way to build, create, and deploy Web applications using Scala and Java. This framework is ideal for 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. The framework has good routing and filtering. It’s available for Java SE/EE, OSGi, Google’s AppEngine (which is part of Google Compute), Android, and many other Java platforms. It’s a self-sufficient framework that even ships with its own webserver.

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";
}
}

Best Practices for Microservices

You should be able to tell by now that making the shift to microservices creates a lot of benefits for development, operations, and the business. They create opportunities for increased scalability, greater reliability, and cost savings. But, there’s no such thing as a free lunch. Microservices come with pitfalls of their own.

Here are some best practices that will help your migration.

Each of your microservices should use their own data store. You want the development (and dev-ops) team to choose the database for each of their service. They should have an opportunity to choose the data store that best suits their project. At the same time, if teams share a database, it’s too easy for them to share a schema, creating a monolithic service under a different name.

Deploying microservices in containers isn’t just a good idea. It’s a best practice, too. I’ve mentioned several times that microservice teams should choose their own tools. How do operations and dev-ops manage the chaos this creates? By using containers, so you can deploy and orchestrate your system with a single set of tools.

There’s a reason why RESTful services and microservices are often associated with each other. It’s because the best microservices architectures treat their services as stateless. REST’s state transfer that pushes state down to the clients means that you can treat your servers as stateless, and run your code as interchangeable parts of a whole. You only need to worry about making sure that there are enough services available to handle the load. And, if one fails, another can pick up the slack.

Additional Resources and Tutorials on Microservices

For further reading and information on microservices, including some helpful tutorials, visit the following resources:

In this article, we’ve discussed what microservices are, and how they can help you improve your enterprise architecture. After defining what these services are, we covered their major benefits. Then we looked at some of the most popular microservice APIs for Java. Then, we wrapped up with a look at microservices best practices and a list of resources here on Stackify’s website.

Microservices are a great addition to your enterprise. But, it helps to have a tool like Retrace to help you monitor them.

Retrace is a code-level APM solution that can manage and monitor your app’s performance throughout the entire development lifecycle. Plus, it offers many other features, such as error tracking, log management, and application metrics.

Start your trial today.

Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]