Example of using Yandex Message Queue on JMS
Written by
Updated at May 13, 2024
JMS
Installation
Install the AWS SDK for Java by following the instructions
Getting started
- Create a service account.
- Assign the editor role to the service account.
- Create a static access key.
Set the environment variables:
export AWS_ACCESS_KEY_ID="<access_key_ID>"
export AWS_SECRET_ACCESS_KEY="<secret_key>"
Create a queue in Message Queue and prepare its URL.
Example
To run the example, add these dependencies:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>amazon-sqs-java-messaging-lib</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sqs</artifactId>
<version>1.11.176</version>
</dependency>
</dependencies>
In this example:
- A connection with Message Queue is established.
- A message queue is created.
- A message with the text
test-message
is sent to the queue. - The message is read from the queue and displayed in the terminal.
To read about the features not covered by the example, see the documentation on the AWS SQS Java Messaging Library
package ru.yandex.cloud.message_queue;
import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper;
import com.amazon.sqs.javamessaging.SQSConnection;
import com.amazon.sqs.javamessaging.SQSConnectionFactory;
import com.amazon.sqs.javamessaging.ProviderConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import javax.jms.*;
public class App
{
private static String queueName = "mq_jms_example";
public static void main( String[] args ) throws JMSException
{
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
new ProviderConfiguration(),
AmazonSQSClientBuilder.standard()
.withRegion("ru-central1")
.withEndpointConfiguration(new EndpointConfiguration(
"https://message-queue.api.cloud.yandex.net",
"ru-central1"
))
);
SQSConnection connection = connectionFactory.createConnection();
AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();
if( !client.queueExists(queueName) ) {
client.createQueue( queueName );
}
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
MessageProducer producer = session.createProducer(queue);
Message message = session.createTextMessage("test message");
producer.send(message);
MessageConsumer consumer = session.createConsumer(queue);
connection.start();
message = consumer.receive(1000);
System.out.println(((TextMessage) message).getText());
}
}