-
Notifications
You must be signed in to change notification settings - Fork 43
[EDU-1977] - Added Java getting started guide for Pub/Sub #2713
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,246 @@ | ||||||
--- | ||||||
title: "Getting started: Pub/Sub in Java" | ||||||
meta_description: "A getting started guide for Ably Pub/Sub Java that steps through some of the key features using Java." | ||||||
meta_keywords: "Pub/Sub Java, Java PubSub, Ably Java SDK, realtime messaging Java, publish subscribe Java, Ably Pub/Sub guide, Java realtime communication, Ably tutorial Java, Java message history, presence API Java, Ably Pub/Sub example, realtime Pub/Sub Java, subscribe to channel Java, publish message Java, Ably CLI Pub/Sub" | ||||||
languages: | ||||||
- java | ||||||
--- | ||||||
|
||||||
This guide will get you started with Ably Pub/Sub in Java. | ||||||
|
||||||
It will take you through the following steps: | ||||||
|
||||||
* Create a client and establish a realtime connection to Ably. | ||||||
* Attach to a channel and subscribe to its messages. | ||||||
* Publish a message to the channel for your client to receive. | ||||||
* Join and subscribe to the presence set of the channel. | ||||||
* Retrieve the messages you sent in the guide from history. | ||||||
* Close a connection to Ably when it is no longer needed. | ||||||
|
||||||
h2(#prerequisites). Prerequisites | ||||||
|
||||||
* "Sign up":https://ably.com/sign-up for an Ably account. | ||||||
** Create a new app and get your API key from the "dashboard":https://ably.com/dashboard. | ||||||
** Your API key will need the @publish@, @subscribe@, @presence@ and @history@ "capabilities":/docs/auth/capabilities. | ||||||
|
||||||
* Install the Ably CLI: | ||||||
|
||||||
```[sh] | ||||||
npm install -g @ably/cli | ||||||
``` | ||||||
|
||||||
* Run the following to log in to your Ably account and set the default app and API key: | ||||||
|
||||||
```[sh] | ||||||
ably login | ||||||
|
||||||
ably apps switch | ||||||
ably auth keys switch | ||||||
``` | ||||||
|
||||||
* Install "Java Development Kit (JDK)":"https://adoptium.net/ version 8 or greater. | ||||||
* Create a new project and add the Ably "Pub/Sub Java SDK":https://github.com/ably/ably-java as a dependency. | ||||||
|
||||||
For Maven, add the following to your @pom.xml@: | ||||||
|
||||||
```[xml] | ||||||
<dependency> | ||||||
<groupId>io.ably</groupId> | ||||||
<artifactId>ably-java</artifactId> | ||||||
<version>1.2.22</version> | ||||||
</dependency> | ||||||
``` | ||||||
|
||||||
For Gradle, add the following to your @build.gradle@: | ||||||
|
||||||
```[text] | ||||||
implementation 'io.ably:ably-java:1.2.22' | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here |
||||||
implementation 'org.slf4j:slf4j-simple:2.0.7' | ||||||
``` | ||||||
|
||||||
<aside data-type='note'> | ||||||
<p>The code examples in this guide include a demo API key. If you wish to interact with the Ably CLI and view outputs within your Ably account, ensure that you replace them with your own API key.</p> | ||||||
</aside> | ||||||
|
||||||
h2(#step-1). 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":https://ably.com/accounts/any/apps/any/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 a production app. A @clientId@ ensures the client is identified, which is required to use certain features, such as presence: | ||||||
|
||||||
```[java] | ||||||
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("{{API_KEY}}"); | ||||||
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(); | ||||||
} | ||||||
} | ||||||
} | ||||||
``` | ||||||
|
||||||
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. | ||||||
|
||||||
h2(#step-2). 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] | ||||||
// 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. | ||||||
|
||||||
```[sh] | ||||||
ably channels publish my-first-channel 'Hello!' --name "myEvent" | ||||||
``` | ||||||
|
||||||
* In a new terminal tab, subscribe to the same channel using the CLI: | ||||||
|
||||||
```[sh] | ||||||
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] | ||||||
channel.publish("", "A message sent from my first client!"); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. don't like empty strings, I think it's better to use some text for name: "message" or "update" |
||||||
``` | ||||||
|
||||||
h2(#step-3). 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] | ||||||
// Subscribe to presence events on the channel | ||||||
channel.presence.subscribe(presenceMessage -> { | ||||||
System.out.println("Event type: " + presenceMessage.action + | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
" 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: | ||||||
|
||||||
```[sh] | ||||||
ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}' | ||||||
``` | ||||||
|
||||||
h2(#step-4). 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. This can be extended for longer 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: | ||||||
|
||||||
```[sh] | ||||||
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] | ||||||
// 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] | ||||||
[ | ||||||
'Message number 5', | ||||||
'Message number 4', | ||||||
'Message number 3', | ||||||
'Message number 2', | ||||||
'Message number 1' | ||||||
] | ||||||
``` | ||||||
|
||||||
h2(#step-5). Step 5: Close the connection | ||||||
|
||||||
Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client. | ||||||
|
||||||
Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call @subscribe()@. Detaching from a channel using the @detach()@ method will stop the client from being streamed messages by Ably. | ||||||
|
||||||
Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling @unsubscribe()@ will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment. | ||||||
|
||||||
* Replace the line @Thread.sleep(2000);@ with the following to your client to close the connection after a simulated 10 seconds. Run it with @./gradlew run@: | ||||||
|
||||||
```[java] | ||||||
// Close the connection after 10 seconds | ||||||
new Thread(() -> { | ||||||
try { | ||||||
Thread.sleep(10000); | ||||||
realtime.close(); | ||||||
System.out.println("Connection closed after 10 seconds."); | ||||||
System.exit(0); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think we need |
||||||
} catch (AblyException e) { | ||||||
e.printStackTrace(); | ||||||
} | ||||||
}).start(); | ||||||
``` | ||||||
|
||||||
h2(#next). Next steps | ||||||
|
||||||
Continue to explore the documentation with Java as the selected language: | ||||||
|
||||||
Read more about the concepts covered in this guide: | ||||||
|
||||||
* Revisit the basics of "Pub/Sub":/docs/pub-sub?lang=java | ||||||
* Explore more "advanced":/docs/pub-sub/advanced?lang=java Pub/Sub concepts | ||||||
* Understand realtime "connections":/docs/connect?lang=java to Ably | ||||||
* Read more about how to use "presence":/docs/presence-occupancy/presence?lang=java in your apps | ||||||
* Fetch message "history":/docs/storage-history/history?lang=java in your apps | ||||||
|
||||||
You can also explore the Ably CLI further, or visit the Pub/Sub "API references":/docs/api/realtime-sdk?lang=java. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's put the latest version we had for now 1.2.52