Example of using Yandex Message Queue on JMS
Written by
JMS is an API for sending messages between application components. With the AWS SQS Java Messaging Library, you can use Message Queue to send and receive messages via JMS.
Installation
Install the SDK for Java by following the instructions on the official website.
Before you start
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
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 website.
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 = "ymq_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());
}
}