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
- Sign up for an Ably account.
- Create a new app, and create your first API key in the API Keys tab of the dashboard.
- Your API key will need the
publish,subscribe,presenceandhistorycapabilities. - Install Java Development Kit (JDK) version 8 or greater.
- 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.pubsub</groupId>
<artifactId>device-jvm</artifactId>
<version>2.0.0</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.pubsub:device:2.0.0'
implementation 'org.slf4j:slf4j-simple:2.0.7'(Optional) Install Ably CLI
Use the Ably CLI as an additional client to quickly test Pub/Sub features. It can simulate other clients by publishing messages, subscribing to channels, and managing presence states.
ably init installs the Ably CLI, authenticates, and sets the default app and API key in a single command:
npx @ably/cli initStep 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19