DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Tech Hiring: Trends, Predictions, and Strategies for Success
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • AI and Cybersecurity Protecting Against Emerging Threats
  • Getting Started With Istio in AWS EKS for Multicluster Setup

Trending

  • Tech Hiring: Trends, Predictions, and Strategies for Success
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • AI and Cybersecurity Protecting Against Emerging Threats
  • Getting Started With Istio in AWS EKS for Multicluster Setup
  1. DZone
  2. Data Engineering
  3. Data
  4. Ultra-Fast Microservices: When MicroStream Meets Wildfly

Ultra-Fast Microservices: When MicroStream Meets Wildfly

In the second part of the ultra-fast series, In this article, learn a new database that can make your microservices scale up quickly in the Java world!

Otavio Santana user avatar by
Otavio Santana
CORE ·
Updated May. 10, 22 · Tutorial
Like (9)
Save
Tweet
Share
16.40K Views

Join the DZone community and get the full member experience.

Join For Free

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 Wildfly to create a microservice application that is easily stable and ultra-fast.

Microservices With Wildfly

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 a REST Client, Configuration, Open API, etc.

Wildfly is a powerful, modular, and lightweight application server that helps you build amazing applications.

Data Persistence Really Fast With MicroStream

When we talk about microservices, we speak about the distributed system and its challenges, and this 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 statelessness, 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 a 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 Wildfly, 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.

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/wildfly-example-bootable.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 Wildfly and MicroStream working. This tutorial shows how both work together and gives you a new tool to face persistence issues: MicroStream. Indeed MicroStream and Wildfly are great allies when you want to create microservices to run it ultra-fast.

References

  • The code sample

  • MicroStream documentation

  • Wildfly documentation

Database WildFly application Inventory (library) microservice Data Types

Opinions expressed by DZone contributors are their own.

Trending

  • Tech Hiring: Trends, Predictions, and Strategies for Success
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • AI and Cybersecurity Protecting Against Emerging Threats
  • Getting Started With Istio in AWS EKS for Multicluster Setup

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: