Getting started: Pub/Sub in Java

This guide will get you started with Ably Pub/Sub in Java.

You'll establish a realtime connection to Ably and learn to publish and subscribe to messages. You'll also implement presence to track other online clients, and learn how to retrieve message history.

Prerequisites

  1. Sign up for an Ably account.
  2. Create a new app, and create your first API key in the API Keys tab of the dashboard.
  3. Your API key will need the publish, subscribe, presence and history capabilities.
  4. Install Java Development Kit (JDK) version 8 or greater.
  5. Create a new project and add the Ably Pub/Sub Java SDK as a dependency.

For Maven, add the following to your pom.xml:

1

2

3

4

5

6

7

8

9

10

<dependency>
    <groupId>io.ably</groupId>
    <artifactId>ably-java</artifactId>
    <version>1.2.52</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.7</version>
</dependency>

For Gradle, add the following to your build.gradle:

1

2

implementation 'io.ably:ably-java:1.2.52'
implementation 'org.slf4j:slf4j-simple:2.0.7'

(Optional) Install Ably CLI

The Ably CLI provides a command-line interface for managing your Ably applications directly from your terminal.

  1. Install the Ably CLI:
npm install -g @ably/cli
  1. Run the following to log in to your Ably account and set the default app and API key:
ably login

Step 1: Connect to Ably

Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.

Open up the dev console of your first app before instantiating your client so that you can see what happens.

Replace the contents of your App.java file with functionality to instantiate the SDK and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in production environments. A clientId ensures the client is identified, which is required to use certain features, such as presence:

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

package ably.java.quickstart;

import io.ably.lib.realtime.AblyRealtime;
import io.ably.lib.realtime.Channel;
import io.ably.lib.realtime.ConnectionEvent;
import io.ably.lib.types.AblyException;
import io.ably.lib.types.ClientOptions;
import io.ably.lib.types.ErrorInfo;
import io.ably.lib.types.Message;
import io.ably.lib.types.PaginatedResult;

public class App {
    public static void main(String[] args) {
        try {
            // Initialize the Ably Realtime client
            ClientOptions options = new ClientOptions("demokey:*****");
            options.clientId = "my-first-client";
            AblyRealtime realtime = new AblyRealtime(options);

            // Wait for the connection to be established
            realtime.connection.on(ConnectionEvent.connected, connectionStateChange -> {
                System.out.println("Made my first connection!");
            });

            // Keep the program running
            Thread.sleep(2000);

        } catch (AblyException e) {
            e.printStackTrace();
        }
    }
}
API key:
DEMO ONLY

You can monitor the lifecycle of clients' connections by registering a listener that will emit an event every time the connection state changes. For now, run the program with ./gradlew run to log a message to the console to know that the connection attempt was successful. You'll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.

Step 2: Subscribe to a channel and publish a message

Messages contain the data that a client is communicating, such as a short 'hello' from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.

Add the following lines to your main method, above the line // Keep the program running, to create a channel instance and register a listener to subscribe to the channel. Then run it with ./gradlew run:

Java

1

2

3

4

5

6

7

// Get a channel instance
Channel channel = realtime.channels.get("my-first-channel");

// Subscribe to messages on the channel
channel.subscribe(message -> {
    System.out.println("Received message: " + message.data);
});

Use the Ably CLI to publish a message to your first channel. The message will be received by the client you've subscribed to the channel, and be logged to the console.

ably channels publish my-first-channel 'Hello!' --name "myEvent"

In a new terminal tab, subscribe to the same channel using the CLI:

ably channels subscribe my-first-channel

Publish another message using the CLI and you will see that it's received instantly by the client you have running locally, as well as the subscribed terminal instance.

To publish a message in your code, you can add the following line to your main method, above the line // Keep the program running, after subscribing to the channel:

Java

1

channel.publish("myEvent", "A message sent from my first client!");

Step 3: Join the presence set

Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline.

Add the following lines to your main method, above the line // Keep the program running, to subscribe to, and join, the presence set of the channel. Then run it with ./gradlew run:

Java

1

2

3

4

5

6

7

8

9

// Subscribe to presence events on the channel
channel.presence.subscribe(presenceMessage -> {
    System.out.println("Event type: " + presenceMessage.action.name() +
                      " from " + presenceMessage.clientId +
                      " with the data " + presenceMessage.data);
});

// Enter the presence set
channel.presence.enter("I'm here!", null);

You can have another client join the presence set using the Ably CLI:

ably channels presence enter my-first-channel --data '{"status":"learning about Ably!"}'

Step 4: Retrieve message history

You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. You can extend the storage period of messages if required.

If more than 2 minutes has passed since you published a regular message (excluding the presence events), then publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.

For example, using the Ably CLI to publish 5 messages:

ably channels publish --count 5 my-first-channel "Message number {{.Count}}" --name "myEvent"

Add the following lines to your main method, above the line // Keep the program running, to retrieve any messages that were recently published to the channel. Then run it with ./gradlew run:

Java

1

2

3

4

5

6

7

8

9

10

11

// Retrieve message history
PaginatedResult<Message> resultPage = channel.history(null);
Message[] messages = resultPage.items();
if (messages.length > 0) {
    System.out.println("Message History:");
    for (Message message : messages) {
        System.out.println(message.data);
    }
} else {
    System.out.println("No messages in history.");
}

The output will look similar to the following:

JSON

1

2

3

4

5

6

7

[
  'Message number 5',
  'Message number 4',
  'Message number 3',
  'Message number 2',
  'Message number 1'
]

Next steps

Continue to explore the documentation with Java as the selected language:

You can also explore the Ably CLI further, or visit the Pub/Sub API references.

Select...