Ultra-Fast Microservices in Java: When Microstream Meets Open Liberty
In this article, learn a new database that can make your microservices scale up quickly in the Java world!
Join the DZone community and get the full member experience.
Join For FreeMicroservices have become a buzzword when we talk about creating a scalable application. But is that enough? The simple answer is no. As with any software architecture decision, it has a trade-off and several challenges. Lucky for us Java developers, there is a combination of two tools to make our life easier: Microstream and MicroProfile. This article will cover combining Microstream and Open Liberty to create a microservice application that is easily stable and ultra-fast.
Microservices With Open Liberty
Microservices provide several challenges to us software engineers, especially as a first step to facing distributed systems. But it does not mean that we're alone. Indeed there are several tools to make our life easier in the Java world, especially, MicroProfile.
MicroProfile has a goal to optimize Enterprise Java for a Microservices Architecture. It is based on the Java EE/Jakarta EE standard plus API specifically for microservices such as Rest Client, Configuration, Open API, etc.
Open Liberty is one of those implementations, and it has IBM as the primary contributor. Open Liberty is a lightweight, open framework for building fast and efficient cloud-native Java microservices. It provides just enough runtime for running cloud-native apps and microservices.
Data Persistence Really Fast With Microstream
Once we talk about microservices, we speak about the distributed system and its challenges, and this summons will be the same in the persistence layer.
Unfortunately, we don't have enough articles that talk about it. We should have a model, even the schemaless databases when you have more uncertain information about the business. Still, the persistence layer has more issues, mainly because it is harder to change.
One of the secrets to making a scalable application is to ensure it is stateless, but we cannot afford it in the persistence layer. Primarily, the database aims to keep the information and its state.
One of the solutions to make your data persistence layer more natural is to integrate directly with the Java Entity as a graph. That is what Microstream does.
Microstream realizes ultra-fast in-memory data processing with pure Java. It provides microsecond query time, low-latency data access, gigantic data throughput, and workloads. Thus it saves lots of CPU power, CO2 emission, and costs in the data center.
Show Me the Code
Let's combine both to make an ultrafast microservice. Once the main goal is to show how both combine, we'll choose a smooth demo. In this sample, we'll create a simple CRUD with a product, its name, and rating and export it as Rest API.
The first step is to create the MicroProfile skeleton: it is effortless and smooth, mainly because we can identify visually with the MicroProfile starter. Set Microprofile version 4.1 with Java 11 and Open Liberty, as the picture shows below.
Yep, we have the skeleton of our application. The next step is to add the Microstream and make both work together. Fortunately, there is a library to integrate both through CDI extension. Thus, any application with CDI and MicroProfile Config can work thanks to this API.
Please look at the latest version and add it to your application.
<dependency>
<groupId>one.microstream</groupId>
<artifactId>microstream-integrations-cdi</artifactId>
<version>LAST_VERSION_HERE</version>
</dependency>
The Skeleton is set, so let's start with the code. The model is the central part. Once it is a smooth sample, we'll create a Product entity with a few fields. The main recommendation to use Microstream is to use immutable entities. Therefore, we'll create a product as an immutable entity.
public class Product {
private final long id;
private final String name;
private final String description;
private final int rating;
@JsonbCreator
public Product(
@JsonbProperty("id") final long id,
@JsonbProperty("name") final String name,
@JsonbProperty("description") final String description,
@JsonbProperty("rating") final int rating
) {
this.id = id;
this.name = name;
this.description = description;
this.rating = rating;
}
JSON annotations only teach MicroProfile how to serialize the entity as JSON.
The next step is defining a collection of products, which we'll call Inventory. The Inventory class is a set of products with several operation methods.
This class is the link between your entity and the Microstream engine. The connection with Microstream is using the Storage
annotation.
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import one.microstream.integrations.cdi.types.Storage;
@Storage
public class Inventory {
private final Set<Product> products = new HashSet<>();
public void add(final Product product) {
Objects.requireNonNull(product, "product is required");
this.products.add(product);
}
public Set<Product> getProducts() {
return Collections.unmodifiableSet(this.products);
}
public Optional<Product> findById(final long id) {
return this.products.stream().filter(this.isIdEquals(id)).limit(1).findFirst();
}
public void deleteById(final long id) {
this.products.removeIf(this.isIdEquals(id));
}
private Predicate<Product> isIdEquals(final long id) {
return p -> p.getId() == id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Inventory inventory = (Inventory) o;
return Objects.equals(products, inventory.products);
}
@Override
public int hashCode() {
return Objects.hash(products);
}
@Override
public String toString() {
return "Inventory{" +
"products=" + products +
'}';
}
}
With the collection ready, let's create the repository. To use our Inventory
class, we can use the Inject
annotation from CDI. We need to commit this operation to each operation that will change this collection. For any method that changes the inventory, there is the Store
annotation that handles it automatically for us.
public interface ProductRepository
{
Collection<Product> getAll();
Product save(Product item);
Optional<Product> findById(long id);
void deleteById(long id);
}
@ApplicationScoped
public class ProductRepositoryStorage implements ProductRepository {
private static final Logger LOGGER = Logger.getLogger(ProductRepositoryStorage.class.getName());
@Inject
private Inventory inventory;
@Override
public Collection<Product> getAll() {
return this.inventory.getProducts();
}
@Override
@Store
public Product save(final Product item) {
this.inventory.add(item);
return item;
}
@Override
public Optional<Product> findById(final long id) {
LOGGER.info("Finding the item by id: " + id);
return this.inventory.findById(id);
}
@Override
@Store
public void deleteById(final long id) {
this.inventory.deleteById(id);
}
}
The last step is to expose this product as a Rest API. Then, we'll return with MicroProfile using the Jakarta EE API: JAX-RS. Next, we'll create Open API documentation using MicroProfile.
@RequestScoped
@Path("products")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ProductController
{
@Inject
private ProductRepository repository;
// TODO don't worried about pagination
@GET
@Operation(summary = "Get all products", description = "Returns all available items at the restaurant")
@APIResponse(responseCode = "500", description = "Server unavailable")
@APIResponse(responseCode = "200", description = "The products")
@Tag(name = "BETA", description = "This API is currently in beta state")
@APIResponse(description = "The products", responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = Collection.class, readOnly = true, description = "the products", required = true, name = "products")))
public Collection<Product> getAll()
{
return this.repository.getAll();
}
@GET
@Path("{id}")
@Operation(summary = "Find a product by id", description = "Find a product by id")
@APIResponse(responseCode = "200", description = "The product")
@APIResponse(responseCode = "404", description = "When the id does not exist")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
@APIResponse(description = "The product", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = Product.class)))
public Product findById(
@Parameter(description = "The item ID", required = true, example = "1", schema = @Schema(type = SchemaType.INTEGER)) @PathParam("id") final long id)
{
return this.repository.findById(id).orElseThrow(
() -> new WebApplicationException("There is no product with the id " + id, Response.Status.NOT_FOUND));
}
@POST
@Operation(summary = "Insert a product", description = "Insert a product")
@APIResponse(responseCode = "201", description = "When creates an product")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
public Response insert(
@RequestBody(description = "Create a new product.", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Product.class))) final Product product)
{
return Response.status(Response.Status.CREATED).entity(this.repository.save(product)).build();
}
@DELETE
@Path("{id}")
@Operation(summary = "Delete a product by ID", description = "Delete a product by ID")
@APIResponse(responseCode = "200", description = "When deletes the product")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
public Response delete(
@Parameter(description = "The item ID", required = true, example = "1", schema = @Schema(type = SchemaType.INTEGER)) @PathParam("id") final long id)
{
this.repository.deleteById(id);
return Response.status(Response.Status.NO_CONTENT).build();
}
}
That is it! We can test out the application running and check the result. The integration works like a charm.
mvn clean package
java -jar target/openliberty-example.jar
curl --location --request POST 'http://localhost:8080/products/' \
--header 'Content-Type: application/json' \
--data-raw '{"id": 1, "name": "banana", "description": "a fruit", "rating": 5}'
curl --location --request POST 'http://localhost:8080/products/' \
--header 'Content-Type: application/json' \
--data-raw '{"id": 2, "name": "watermelon", "description": "watermelon sugar ahh", "rating": 4}'
curl --location --request GET 'http://localhost:8080/products/'
curl --location --request GET 'http://localhost:8080/products/1'
We finally have our integration between Open Liberty and Microstream working. This tutorial shows how both work together and gives you a new tool to face persistence issues: Microstream. Indeed Microstream and Open Liberty are great allies when you want to create microservices to run it ultra-fast.
References
Opinions expressed by DZone contributors are their own.
Comments