Ultra-Fast Microservices: When Microstream Meets Payara

Microservices 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 Payara to create a microservice application that is easily stable and ultra-fast.  Feel free to check out Part 1 and Part 2 as well.

Microservices With Payara

Microservices provide several challenges to 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.

Payara is a Jakarta EE and MicroProfile compatible, a supported application server for production and containerized deployments.

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 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 ultra-fast 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.0 with Java 11 and Payara, as the picture shows below.
Set Microprofile version 4.0 with Java 11 and Payara

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.

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

Java
 
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){
            //...
            }

}


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.

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

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

Java
 
@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
   public Collection<Product> getAll()
  {
    return this.repository.getAll();
  }
  
  @GET
  @Path("{id}")
  @Operation(summary = "Find a product by id", description = "Find a product by id")
   public Product findById(@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
  public Response insert(final Product product)
  {
    return Response.status(Response.Status.CREATED).entity(this.repository.save(product)).build();
  }
  
  @DELETE
  @Path("{id}")
   public Response delete(@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. 

Shell
 
mvn clean package
java -jar target/payara-example-microbundle.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}'


We finally have our integration between Payara and MicroStream working. This tutorial shows how both work together and gives you a new tool to face persistence issues: MicroStream. Indeed MicroStream and Payara are great allies when you want to create microservices to run it ultra-fast.

References and Resources

 

 

 

 

Top