eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

When building Java applications that use MQTT, we need its client library that’s easy to use and well-suited for production. The HiveMQ MQTT Client, developed and maintained by the HiveMQ team, is a modern Java library that supports both MQTT 3.1.1 and MQTT 5.

The client provides multiple API styles, including blocking, asynchronous, and reactive, to support different programming models. Moreover, it exposes a fluent, builder-based API for configuring connections, subscriptions, and publish operations when interacting with an MQTT broker.

In this tutorial, we’ll demonstrate the library’s basic usage. Specifically, we’ll connect to a public MQTT broker, subscribe to a topic, publish a message, and verify message delivery using an integration test.

2. Project Setup

Before we create clients, we have to add the HiveMQ MQTT Client dependency to our project:

<dependency>
    <groupId>com.hivemq</groupId>
    <artifactId>hivemq-mqtt-client</artifactId>
    <version>1.3.12</version>
</dependency>

The latest version of the library module is available on Maven Central.

With the dependency in place, we can create an MQTT client and connect to a publicly available MQTT broker at broker.hivemq.com:1883.

3. Creating the Clients

To illustrate the different API styles of the HiveMQ MQTT Client, we’ll create two clients. We’ll use an asynchronous client to subscribe to topics and receive messages, and a blocking client to publish messages synchronously.

3.1. Creating an Asynchronous Client

First, let’s start with an asynchronous client that subscribes to topics and handles incoming messages in a non-blocking, event-driven way. This client type allows us to register callbacks that are invoked whenever a message arrives.

We’ll create it using the fluent builder API:

Mqtt5AsyncClient subscriber = Mqtt5Client.builder()
  .identifier("baeldung-sub-" + UUID.randomUUID())
  .serverHost(PUBLIC_BROKER_HOST)
  .serverPort(PUBLIC_BROKER_PORT)
  .buildAsync();

With a unique client identifier and the MQTT broker address configured, buildAsync() creates an asynchronous MQTT 5 client instance. Later, we’ll use this client to connect to the broker and subscribe to a topic.

3.2. Creating a Blocking Client

In contrast, we’ll use a blocking client for publishing messages. The blocking API executes operations synchronously, which works well when we don’t need to react to incoming messages.

Similarly, we’ll create the blocking client using the builder API:

Mqtt5BlockingClient publisher = Mqtt5Client.builder()
  .identifier("baeldung-pub-" + UUID.randomUUID())
  .serverHost(PUBLIC_BROKER_HOST)
  .serverPort(PUBLIC_BROKER_PORT)
  .buildBlocking();

After configuring a unique client identifier and the broker address, the call to buildBlocking() creates an MQTT 5 client instance. This client provides synchronous methods for connecting to the broker and publishing messages.

4. Connecting, Subscribing, and Publishing

Now that we have both clients, we can connect to the publicly available broker, subscribe to a topic, and publish a message.

4.1. Connecting to the Broker

First, we’ll connect both clients:

subscriber.connect()
  .join();
publisher.connect();

The asynchronous client returns a CompletableFuture when connecting, so we’ll wait for the connection to complete using join(). On the other hand, the blocking client connects synchronously and returns only after the connection is established.

4.2. Subscribing to a Topic

Next, we’ll register a handler on the asynchronous client to process incoming publishes. We’ll use a latch to let our test wait until the subscriber receives the message:

CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> receivedMessage = new AtomicReference<>();

subscriber.publishes(MqttGlobalPublishFilter.SUBSCRIBED, publish -> {
    String message = new String(publish.getPayloadAsBytes(), StandardCharsets.UTF_8);
    receivedMessage.set(message);
    latch.countDown();
});

The handler defines the message processing logic. When a message arrives, the callback extracts the payload and signals the test thread to continue.

With the handler in place, we can subscribe to our topic:

subscriber.subscribeWith()
  .topicFilter(topic)
  .send()
  .join();

This tells the broker which topic the client wants to receive messages from and waits for confirmation.

4.3. Publishing a Message

Finally, we’ll publish a message using the blocking client:

String payload = "Hello from Baeldung";

publisher.publishWith()
  .topic(topic)
  .payload(payload.getBytes(StandardCharsets.UTF_8))
  .send();

At this point, the broker forwards the published message to all subscribers of the topic. In our case, the callback registered on the asynchronous client receives the message and stores the payload.

5. Verifying Message Delivery

Lastly, to verify that the subscriber received the published message, we’ll add assertions in the test. After the subscriber callback runs, the test checks that the received payload matches the published value:

assertTrue(latch.await(2, TimeUnit.SECONDS));
assertEquals(payload, receivedMessage.get());

After the verification, we’ll disconnect both clients to close the connections to the broker and release resources:

publisher.disconnect();
subscriber.disconnect()
  .join();

As a result, disconnecting the clients releases network resources and completes the client lifecycle.

6. Conclusion

In this article, we introduced the HiveMQ MQTT Client and demonstrated how to connect to a public MQTT broker, subscribe to a topic, publish a message, and verify message delivery using an integration test.

Depending on the use case, developers can choose between blocking APIs for synchronous workflows, asynchronous APIs for event-driven applications, or reactive APIs for stream-based processing. This flexibility makes the HiveMQ MQTT Client suitable for a variety of Java applications.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)