Acknowledging messages using MicroProfile Reactive Messaging

duration 20 minutes

Prerequisites:

Learn how to acknowledge messages by using MicroProfile Reactive Messaging.

What you’ll learn

MicroProfile Reactive Messaging provides a reliable way to handle messages in reactive applications. MicroProfile Reactive Messaging ensures that messages aren’t lost by requiring that messages that were delivered to the target server are acknowledged after they are processed. Every message that gets sent out must be acknowledged. This way, any messages that were delivered to the target service but not processed, for example, due to a system failure, can be identified and sent again.

The application in this guide consists of two microservices, system and inventory. Every 15 seconds, the system microservice calculates and publishes events that contain its current average system load. The inventory microservice subscribes to that information so that it can keep an updated list of all the systems and their current system loads. You can get the current inventory of systems by accessing the /systems REST endpoint. The following diagram depicts the application that is used in this guide:

Reactive system inventory

You will explore the acknowledgment strategies that are available with MicroProfile Reactive Messaging, and you’ll implement your own manual acknowledgment strategy. To learn more about how the reactive Java services used in this guide work, check out the Creating reactive Java microservices guide.

Additional prerequisites

You need to have Docker installed. For installation instructions, refer to the official Docker documentation. You will build and run the microservices in Docker containers. An installation of Apache Kafka is provided in another Docker container.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-reactive-messaging-acknowledgment.git
cd guide-microprofile-reactive-messaging-acknowledgment

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Choosing an acknowledgment strategy

start/SystemService.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2020, 2024 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.system;
13
14import java.lang.management.ManagementFactory;
15import java.lang.management.OperatingSystemMXBean;
16import java.net.InetAddress;
17import java.net.UnknownHostException;
18import java.util.concurrent.TimeUnit;
19import java.util.logging.Logger;
20
21import jakarta.enterprise.context.ApplicationScoped;
22
23import org.eclipse.microprofile.reactive.messaging.Incoming;
24import org.eclipse.microprofile.reactive.messaging.Outgoing;
25import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder;
26import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams;
27import org.reactivestreams.Publisher;
28
29import io.openliberty.guides.models.PropertyMessage;
30import io.openliberty.guides.models.SystemLoad;
31import io.reactivex.rxjava3.core.Flowable;
32
33@ApplicationScoped
34public class SystemService {
35
36    private static Logger logger = Logger.getLogger(SystemService.class.getName());
37
38    private static final OperatingSystemMXBean OS_MEAN =
39            ManagementFactory.getOperatingSystemMXBean();
40    private static String hostname = null;
41
42    private static String getHostname() {
43        if (hostname == null) {
44            try {
45                return InetAddress.getLocalHost().getHostName();
46            } catch (UnknownHostException e) {
47                return System.getenv("HOSTNAME");
48            }
49        }
50        return hostname;
51    }
52
53    @Outgoing("systemLoad")
54    public Publisher<SystemLoad> sendSystemLoad() {
55        return Flowable.interval(15, TimeUnit.SECONDS)
56                       .map((interval -> new SystemLoad(getHostname(),
57                             OS_MEAN.getSystemLoadAverage())));
58    }
59
60    // tag::sendProperty[]
61    @Incoming("propertyRequest")
62    @Outgoing("propertyResponse")
63    public PublisherBuilder<PropertyMessage> sendProperty(String propertyName) {
64        logger.info("sendProperty: " + propertyName);
65        // tag::null[]
66        String propertyValue = System.getProperty(propertyName);
67        if (propertyValue == null) {
68            logger.warning(propertyName + " is not System property.");
69            // tag::returnEmpty[]
70            return ReactiveStreams.empty();
71            // end::returnEmpty[]
72        }
73        // end::null[]
74        // tag::propertyMessage[]
75        PropertyMessage message =
76                new PropertyMessage(getHostname(),
77                                    propertyName,
78                                    System.getProperty(propertyName, "unknown"));
79        return ReactiveStreams.of(message);
80        // end::propertyMessage[]
81    }
82    // end::sendProperty[]
83}

Messages must be acknowledged in reactive applications. Messages are either acknowledged explicitly, or messages are acknowledged implicitly by MicroProfile Reactive Messaging. Acknowledgment for incoming messages is controlled by the @Acknowledgment annotation in MicroProfile Reactive Messaging. If the @Acknowledgment annotation isn’t explicitly defined, then the default acknowledgment strategy applies, which depends on the method signature. Only methods that receive incoming messages and are annotated with the @Incoming annotation must acknowledge messages. Methods that are annotated only with the @Outgoing annotation don’t need to acknowledge messages because messages aren’t being received and MicroProfile Reactive Messaging requires only that received messages are acknowledged.

Almost all of the methods in this application that require message acknowledgment are assigned the POST_PROCESSING strategy by default. If the acknowledgment strategy is set to POST_PROCESSING, then MicroProfile Reactive Messaging acknowledges the message based on whether the annotated method emits data:

  • If the method emits data, the incoming message is acknowledged after the outgoing message is acknowledged.

  • If the method doesn’t emit data, the incoming message is acknowledged after the method or processing completes.

It’s important that the methods use the POST_PROCESSING strategy because it fulfills the requirement that a message isn’t acknowledged until after the message is fully processed. This processing strategy is beneficial in situations where messages must reliably not get lost. When the POST_PROCESSING acknowledgment strategy can’t be used, the MANUAL strategy can be used to fulfill the same requirement. In situations where message acknowledgment reliability isn’t important and losing messages is acceptable, the PRE_PROCESSING strategy might be appropriate.

The only method in the guide that doesn’t default to the POST_PROCESSING strategy is the sendProperty() method in the system service. The sendProperty() method receives property requests from the inventory service. For each property request, if the property that’s being requested is valid, then the method creates and returns a PropertyMessage object with the value of the property. However, if the propertyName requested property doesn’t exist, the request is ignored and no property response is returned.

A key difference exists between when a property response is returned and when a property response isn’t returned. In the case where a property response is returned, the request doesn’t finish processing until the response is sent and safely stored by the Kafka broker. Only then is the incoming message acknowledged. However, in the case where the requested property doesn’t exist and a property response isn’t returned, the method finishes processing the request message so the message must be acknowledged immediately.

This case where a message either needs to be acknowledged immediately or some time later is one of the situations where the MANUAL acknowledgment strategy would be beneficial

Implementing the MANUAL acknowledgment strategy

Navigate to the start directory to begin.

Update the SystemService.sendProperty method to use the MANUAL acknowledgment strategy, which fits the method processing requirements better than the default PRE_PROCESSING strategy.

Replace the SystemService class.
system/src/main/java/io/openliberty/guides/system/SystemService.java

finish/SystemService.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2024 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.guides.system;
 13
 14import java.lang.management.ManagementFactory;
 15import java.lang.management.OperatingSystemMXBean;
 16import java.net.InetAddress;
 17import java.net.UnknownHostException;
 18import java.util.concurrent.TimeUnit;
 19import java.util.logging.Logger;
 20
 21import jakarta.enterprise.context.ApplicationScoped;
 22
 23import org.eclipse.microprofile.reactive.messaging.Acknowledgment;
 24import org.eclipse.microprofile.reactive.messaging.Incoming;
 25import org.eclipse.microprofile.reactive.messaging.Message;
 26import org.eclipse.microprofile.reactive.messaging.Outgoing;
 27import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder;
 28import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams;
 29import org.reactivestreams.Publisher;
 30
 31import io.openliberty.guides.models.PropertyMessage;
 32import io.openliberty.guides.models.SystemLoad;
 33import io.reactivex.rxjava3.core.Flowable;
 34
 35@ApplicationScoped
 36public class SystemService {
 37
 38    private static Logger logger = Logger.getLogger(SystemService.class.getName());
 39
 40    private static final OperatingSystemMXBean OS_MEAN =
 41            ManagementFactory.getOperatingSystemMXBean();
 42    private static String hostname = null;
 43
 44    private static String getHostname() {
 45        if (hostname == null) {
 46            try {
 47                return InetAddress.getLocalHost().getHostName();
 48            } catch (UnknownHostException e) {
 49                return System.getenv("HOSTNAME");
 50            }
 51        }
 52        return hostname;
 53    }
 54
 55    @Outgoing("systemLoad")
 56    public Publisher<SystemLoad> sendSystemLoad() {
 57        return Flowable.interval(15, TimeUnit.SECONDS)
 58                       .map((interval -> new SystemLoad(getHostname(),
 59                             OS_MEAN.getSystemLoadAverage())));
 60    }
 61
 62    // tag::sendProperty[]
 63    @Incoming("propertyRequest")
 64    @Outgoing("propertyResponse")
 65    // tag::ackAnnotation[]
 66    @Acknowledgment(Acknowledgment.Strategy.MANUAL)
 67    // end::ackAnnotation[]
 68    // tag::methodSignature[]
 69    public PublisherBuilder<Message<PropertyMessage>>
 70    sendProperty(Message<String> propertyMessage) {
 71    // end::methodSignature[]
 72        // tag::propertyValue[]
 73        String propertyName = propertyMessage.getPayload();
 74        String propertyValue = System.getProperty(propertyName, "unknown");
 75        // end::propertyValue[]
 76        logger.info("sendProperty: " + propertyValue);
 77        // tag::invalid[]
 78        if (propertyName == null
 79        || propertyName.isEmpty()
 80        || propertyValue == "unknown") {
 81            logger.warning("Provided property: "
 82            + propertyName + " is not a system property");
 83            // tag::propertyMessageAck[]
 84            propertyMessage.ack();
 85            // end::propertyMessageAck[]
 86            // tag::emptyReactiveStream[]
 87            return ReactiveStreams.empty();
 88            // end::emptyReactiveStream[]
 89        }
 90        // end::invalid[]
 91        // tag::returnMessage[]
 92        Message<PropertyMessage> message = Message.of(
 93                new PropertyMessage(getHostname(),
 94                        propertyName,
 95                        propertyValue),
 96                propertyMessage::ack
 97        );
 98        return ReactiveStreams.of(message);
 99        // end::returnMessage[]
100    }
101    // end::sendProperty[]
102}

The sendProperty() method needs to manually acknowledge the incoming messages, so it is annotated with the @Acknowledgment(Acknowledgment.Strategy.MANUAL) annotation. This annotation sets the method up to expect an incoming message. To meet the requirements of acknowledgment, the method parameter is updated to receive and return a Message of type String, rather than just a String. Then, the propertyName is extracted from the propertyMessage incoming message using the getPayload() method and checked for validity. One of the following outcomes occurs:

  • If the propertyName system property isn’t valid, the ack() method acknowledges the incoming message and returns an empty reactive stream using the empty() method. The processing is complete.

  • If the system property is valid, the method creates a Message object with the value of the requested system property and sends it to the proper channel. The method acknowledges the incoming message only after the sent message is acknowledged.

Waiting for a message to be acknowledged

The inventory service contains an endpoint that accepts PUT requests. When a PUT request that contains a system property is made to the inventory service, the inventory service sends a message to the system service. The message from the inventory service requests the value of the system property from the system service. Currently, a 200 response code is returned without confirming whether the sent message was acknowledged. Replace the inventory service to return a 200 response only after the outgoing message is acknowledged.

Replace the InventoryResource class.
inventory/src/main/java/io/openliberty/guides/inventory/InventoryResource.java

InventoryResource.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2024 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.guides.inventory;
 13
 14import java.util.List;
 15import java.util.Optional;
 16import java.util.Properties;
 17import java.util.concurrent.CompletableFuture;
 18import java.util.concurrent.CompletionStage;
 19import java.util.logging.Logger;
 20import java.util.stream.Collectors;
 21
 22import jakarta.enterprise.context.ApplicationScoped;
 23import jakarta.inject.Inject;
 24import jakarta.ws.rs.Consumes;
 25import jakarta.ws.rs.DELETE;
 26import jakarta.ws.rs.GET;
 27import jakarta.ws.rs.PUT;
 28import jakarta.ws.rs.Path;
 29import jakarta.ws.rs.PathParam;
 30import jakarta.ws.rs.Produces;
 31import jakarta.ws.rs.core.MediaType;
 32import jakarta.ws.rs.core.Response;
 33
 34import org.eclipse.microprofile.reactive.messaging.Incoming;
 35import org.eclipse.microprofile.reactive.messaging.Message;
 36import org.eclipse.microprofile.reactive.messaging.Outgoing;
 37import org.reactivestreams.Publisher;
 38
 39import io.openliberty.guides.models.PropertyMessage;
 40import io.openliberty.guides.models.SystemLoad;
 41import io.reactivex.rxjava3.core.BackpressureStrategy;
 42import io.reactivex.rxjava3.core.Flowable;
 43import io.reactivex.rxjava3.core.FlowableEmitter;
 44
 45
 46@ApplicationScoped
 47@Path("/inventory")
 48public class InventoryResource {
 49
 50    private static Logger logger = Logger.getLogger(InventoryResource.class.getName());
 51    // tag::propertyNameEmitter[]
 52    private FlowableEmitter<Message<String>> propertyNameEmitter;
 53    // end::propertyNameEmitter[]
 54
 55    @Inject
 56    private InventoryManager manager;
 57
 58    @GET
 59    @Path("/systems")
 60    @Produces(MediaType.APPLICATION_JSON)
 61    public Response getSystems() {
 62        List<Properties> systems = manager.getSystems()
 63                                          .values()
 64                                          .stream()
 65                                          .collect(Collectors.toList());
 66        return Response.status(Response.Status.OK)
 67                       .entity(systems)
 68                       .build();
 69    }
 70
 71    @GET
 72    @Path("/systems/{hostname}")
 73    @Produces(MediaType.APPLICATION_JSON)
 74    public Response getSystem(@PathParam("hostname") String hostname) {
 75        Optional<Properties> system = manager.getSystem(hostname);
 76        if (system.isPresent()) {
 77            return Response.status(Response.Status.OK)
 78                           .entity(system)
 79                           .build();
 80        }
 81        return Response.status(Response.Status.NOT_FOUND)
 82                       .entity("hostname does not exist.")
 83                       .build();
 84    }
 85
 86    // tag::updateSystemProperty[]
 87    @PUT
 88    @Path("/data")
 89    @Produces(MediaType.APPLICATION_JSON)
 90    @Consumes(MediaType.TEXT_PLAIN)
 91    /* This method sends a message and returns a CompletionStage that doesn't
 92        complete until the message is acknowledged. */
 93    // tag::USPHeader[]
 94    public CompletionStage<Response> updateSystemProperty(String propertyName) {
 95    // end::USPHeader[]
 96        logger.info("updateSystemProperty: " + propertyName);
 97        // First, create an incomplete CompletableFuture named "result".
 98        // tag::CompletableFuture[]
 99        CompletableFuture<Void> result = new CompletableFuture<>();
100        // end::CompletableFuture[]
101
102        // Create a message that holds the payload.
103        // tag::message[]
104        Message<String> message = Message.of(
105                // tag::payload[]
106                propertyName,
107                // end::payload[]
108                // tag::acknowledgeAction[]
109                () -> {
110                    /* This is the ack callback, which runs when the outgoing
111                        message is acknowledged. After the outgoing message is
112                        acknowledged, complete the "result" CompletableFuture. */
113                    result.complete(null);
114                    /* An ack callback must return a CompletionStage that says
115                        when it's complete. Asynchronous processing isn't necessary
116                        so a completed CompletionStage is returned to indicate that
117                        the work here is done. */
118                    return CompletableFuture.completedFuture(null);
119                }
120                // end::acknowledgeAction[]
121        );
122        // end::message[]
123
124        // Send the message
125        propertyNameEmitter.onNext(message);
126        /* Set up what happens when the message is acknowledged and the "result"
127            CompletableFuture is completed. When "result" completes, the Response
128            object is created with the status code and message. */
129        // tag::returnResult[]
130        return result.thenApply(a -> Response
131                 .status(Response.Status.OK)
132                 .entity("Request successful for the " + propertyName + " property\n")
133                 .build());
134        // end::returnResult[]
135    }
136    // end::updateSystemProperty[]
137
138    @DELETE
139    @Produces(MediaType.APPLICATION_JSON)
140    public Response resetSystems() {
141        manager.resetSystems();
142        return Response.status(Response.Status.OK)
143                       .build();
144    }
145
146    @Incoming("systemLoad")
147    public void updateStatus(SystemLoad sl)  {
148        String hostname = sl.hostname;
149        if (manager.getSystem(hostname).isPresent()) {
150            manager.updateCpuStatus(hostname, sl.loadAverage);
151            logger.info("Host " + hostname + " was updated: " + sl);
152        } else {
153            manager.addSystem(hostname, sl.loadAverage);
154            logger.info("Host " + hostname + " was added: " + sl);
155        }
156    }
157
158    @Incoming("addSystemProperty")
159    public void getPropertyMessage(PropertyMessage pm)  {
160        logger.info("getPropertyMessage: " + pm);
161        String hostId = pm.hostname;
162        if (manager.getSystem(hostId).isPresent()) {
163            manager.updatePropertyMessage(hostId, pm.key, pm.value);
164            logger.info("Host " + hostId + " was updated: " + pm);
165        } else {
166            manager.addSystem(hostId, pm.key, pm.value);
167            logger.info("Host " + hostId + " was added: " + pm);
168        }
169    }
170
171    // tag::sendPropertyName[]
172    @Outgoing("requestSystemProperty")
173    // tag::SPMHeader[]
174    public Publisher<Message<String>> sendPropertyName() {
175    // end::SPMHeader[]
176        Flowable<Message<String>> flowable = Flowable.create(emitter ->
177            this.propertyNameEmitter = emitter, BackpressureStrategy.BUFFER);
178        return flowable;
179    }
180    // end::sendPropertyName[]
181}

The sendPropertyName() method is updated to return a Message<String> instead of just a String. This return type allows the method to set a callback that runs after the outgoing message is acknowledged. In addition to updating the sendPropertyName() method, the propertyNameEmitter variable is updated to send a Message<String> type.

The updateSystemProperty() method now returns a CompletionStage object wrapped around a Response type. This return type allows for a response object to be returned after the outgoing message is acknowledged. The outgoing message is created with the requested property name as the payload and an acknowledgment callback to execute an action after the message is acknowledged. The method creates a CompletableFuture variable that returns a 200 response code after the variable is completed in the callback function.

Building and running the application

Build the system and inventory microservices using Maven and then run them in Docker containers.

Start your Docker environment. Dockerfiles are provided for you to use.

To build the application, run the Maven install and package goals from the command-line session in the start directory:

mvn -pl models install
mvn package

Run the following commands to containerize the microservices:

docker build -t system:1.0-SNAPSHOT system/.
docker build -t inventory:1.0-SNAPSHOT inventory/.

Next, use the provided script to start the application in Docker containers. The script creates a network for the containers to communicate with each other. It also creates containers for Kafka and the microservices in the project. For simplicity, the script starts one instance of the system service.

.\scripts\startContainers.bat
./scripts/startContainers.sh

Testing the application

The application might take some time to become available. After the application is up and running, you can access it by making a GET request to the /systems endpoint of the inventory service.

Visit the http://localhost:9085/health URL to confirm that the inventory microservice is up and running.

When both the liveness and readiness health checks are up, go to the http://localhost:9085/inventory/systems URL to access the inventory microservice. Look for the CPU systemLoad property for all the systems:

{
   "hostname":"30bec2b63a96",
   "systemLoad":1.44
}

The system service sends messages to the inventory service every 15 seconds. The inventory service processes and acknowledges each incoming message, ensuring that no system message is lost.

If you revisit the http://localhost:9085/inventory/systems URL after a while, you notice that the CPU systemLoad property for the systems changed.

Make a PUT request to the http://localhost:9085/inventory/data URL to add the value of a particular system property to the set of existing properties. For example, run the following curl command:

If curl is unavailable on your computer, use another client such as Postman, which allows requests to be made with a graphical interface.

curl -X PUT -d "os.name" http://localhost:9085/inventory/data --header "Content-Type:text/plain"

In this example, the PUT request with the os.name system property in the request body on the http://localhost:9085/inventory/data URL adds the os.name system property for your system. The inventory service sends a message that contains the requested system property to the system service. The inventory service then waits until the message is acknowledged before it sends a response back.

You see the following output:

Request successful for the os.name property

The previous example response is confirmation that the sent request message was acknowledged.

Revisit the http://localhost:9085/inventory/systems URL and see the os.name system property value is now included with the previous values:

{
   "hostname":"30bec2b63a96",
   "os.name":"Linux",
   "systemLoad":1.44
}

Tearing down the environment

Finally, run the following script to stop the application:

.\scripts\stopContainers.bat
./scripts/stopContainers.sh

Great work! You’re done!

You developed an application by using MicroProfile Reactive Messaging, Open Liberty, and Kafka.

Guide Attribution

Acknowledging messages using MicroProfile Reactive Messaging by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star