Getting started: Creating and connecting to an ActiveMQ broker
A broker is a message broker environment running on Amazon MQ. It is the basic building block of Amazon MQ. The combined description of the
broker instance class (m5
, t3
) and
size (large
, micro
) is a
broker instance type (for example, mq.m5.large
). For more information, see What is an Amazon MQ for ActiveMQ broker?.
Step 1: Create an ActiveMQ broker
The first and most common Amazon MQ task is creating a broker. The following example shows how you can use the AWS Management Console to create a basic broker.
Sign in to the Amazon MQ console
. -
On the Select broker engine page, choose Apache ActiveMQ.
-
On the Select deployment and storage page, in the Deployment mode and storage type section, do the following:
-
Choose the Deployment mode (for example, Active/standby broker). For more information, see Deployment options for Amazon MQ for ActiveMQ brokers.
-
A Single-instance broker is comprised of one broker in one Availability Zone. The broker communicates with your application and with an Amazon EBS or Amazon EFS storage volume. For more information, see Option 1: Amazon MQ single-instance brokers.
-
An Active/standby broker for high availability is comprised of two brokers in two different Availability Zones, configured in a redundant pair. These brokers communicate synchronously with your application, and with Amazon EFS. For more information, see Option 2: Amazon MQ active/standby brokers for high availability.
-
For more information on the sample blueprints for a network of brokers, see Sample blueprints.
-
-
Choose the Storage type (for example, EBS). For more information, see Storage.
Note
Amazon EBS replicates data within a single Availability Zone and doesn't support the ActiveMQ active/standby deployment mode.
Choose Next.
-
-
On the Configure settings page, in the Details section, do the following:
-
Enter the Broker name.
Important
Do not add personally identifiable information (PII) or other confidential or sensitive information in broker names. Broker names are accessible to other AWS services, including CloudWatch Logs. Broker names are not intended to be used for private or sensitive data.
Choose the Broker instance type (for example, mq.m5.large). For more information, see Broker instance types.
-
-
In the ActiveMQ Web Console access section, provide a Username and Password. The following restrictions apply to broker usernames and passwords:
-
Your username can contain only alphanumeric characters, dashes, periods, underscores, and tildas (- . _ ~).
-
Your password must be at least 12 characters long, contain at least 4 unique characters and must not contain commas, colons, or equal signs (,:=).
Important
Do not add personally identifiable information (PII) or other confidential or sensitive information in broker usernames. Broker usernames are accessible to other AWS services, including CloudWatch Logs. Broker usernames are not intended to be used for private or sensitive data.
-
-
Choose Deploy.
While Amazon MQ creates your broker, it displays the Creation in progress status.
Creating the broker takes about 15 minutes.
When your broker is created successfully, Amazon MQ displays the Running status.
-
Choose
MyBroker
.On the
MyBroker
page, in the Connect section, note your broker's ActiveMQ web consoleURL, for example: https://b-1234a5b6-78cd-901e-2fgh-3i45j6k178l9-1.mq.us-east-2.amazonaws.com:8162
Also, note your broker's wire-level protocol Endpoints
. The following is an example of an OpenWire endpoint: ssl://b-1234a5b6-78cd-901e-2fgh-3i45j6k178l9-1.mq.us-east-2.amazonaws.com:61617
Step 2: Connect a Java application to your broker
After you create an Amazon MQ ActiveMQ broker, you can connect your application to it. The following examples show how you can use the Java Message Service (JMS) to create a connection to the broker, create a queue, and send a message. For a complete, working Java example, see Working Java Example.
You can connect to ActiveMQ brokers using various ActiveMQ clients
Prerequisites
Enable VPC attributes
Note
You cannot disable public accessibility for your existing Amazon MQ brokers.
To ensure that your broker is accessible within your VPC, you must enable the enableDnsHostnames
and enableDnsSupport
VPC attributes. For more information, see DNS Support in your VPC in the Amazon VPC User Guide.
Enable inbound connections
Next, use the following instructions to enable inbound connections for your broker.
Sign in to the Amazon MQ console
. From the broker list, choose the name of your broker (for example, MyBroker).
-
On the
MyBroker
page, in the Connections section, note the addresses and ports of the broker's web console URL and wire-level protocols. -
In the Details section, under Security and network, choose the name of your security group or .
The Security Groups page of the EC2 Dashboard is displayed.
-
From the security group list, choose your security group.
-
At the bottom of the page, choose Inbound, and then choose Edit.
-
In the Edit inbound rules dialog box, add a rule for every URL or endpoint that you want to be publicly accessible (the following example shows how to do this for a broker web console).
-
Choose Add Rule.
-
For Type, select Custom TCP.
-
For Port Range, type the web console port (
8162
). -
For Source, leave Custom selected and then type the IP address of the system that you want to be able to access the web console (for example,
192.0.2.1
). -
Choose Save.
Your broker can now accept inbound connections.
-
Add Java dependencies
Add the activemq-client.jar
and activemq-pool.jar
packages to
your Java class path. The following example shows these dependencies in a Maven project pom.xml
file.
<dependencies> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-client</artifactId> <version>5.15.16</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.15.16</version> </dependency> </dependencies>
For more information about activemq-client.jar
, see Initial
Configuration
Important
In the following example code, producers and consumers run in a single thread. For production systems (or to test broker instance failover), make sure that your producers and consumers run on separate hosts or threads.
Create a message producer and send a message
Next, verify your broker can recieve a message by creating a message producer and sending a message.
-
Create a JMS pooled connection factory for the message producer using your broker's endpoint and then call the
createConnection
method against the factory.Note
For an active/standby broker, Amazon MQ provides two ActiveMQ Web Console URLs, but only one URL is active at a time. Likewise, Amazon MQ provides two endpoints for each wire-level protocol, but only one endpoint is active in each pair at a time. The
-1
and-2
suffixes denote a redundant pair. For more information, see Deployment options for Amazon MQ for ActiveMQ brokers).For wire-level protocol endpoints, you can allow your application to connect to either endpoint by using the Failover Transport
. // Create a connection factory. final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(wireLevelEndpoint); // Pass the sign-in credentials. connectionFactory.setUserName(activeMqUsername); connectionFactory.setPassword(activeMqPassword); // Create a pooled connection factory. final PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(); pooledConnectionFactory.setConnectionFactory(connectionFactory); pooledConnectionFactory.setMaxConnections(10); // Establish a connection for the producer. final Connection producerConnection = pooledConnectionFactory.createConnection(); producerConnection.start(); // Close all connections in the pool. pooledConnectionFactory.clear();
Note
Message producers should always use the
PooledConnectionFactory
class. For more information, see Always Use Connection Pooling. -
Create a session, a queue named
MyQueue
, and a message producer.// Create a session. final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create a queue named "MyQueue". final Destination producerDestination = producerSession.createQueue("MyQueue"); // Create a producer from the session to the queue. final MessageProducer producer = producerSession.createProducer(producerDestination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
-
Create the message string
"Hello from Amazon MQ!"
and then send the message.// Create a message. final String text = "Hello from Amazon MQ!"; TextMessage producerMessage = producerSession.createTextMessage(text); // Send the message. producer.send(producerMessage); System.out.println("Message sent.");
-
Clean up the producer.
producer.close(); producerSession.close(); producerConnection.close();
Create a message consumer and receive the message
After creating a producer, create a consumer to verify it can recieve the message.
-
Create a JMS connection factory for the message producer using your broker's endpoint and then call the
createConnection
method against the factory.// Create a connection factory. final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(wireLevelEndpoint); // Pass the sign-in credentials. connectionFactory.setUserName(activeMqUsername); connectionFactory.setPassword(activeMqPassword); // Establish a connection for the consumer. final Connection consumerConnection = connectionFactory.createConnection(); consumerConnection.start();
Note
Message consumers should never use the
PooledConnectionFactory
class. For more information, see Always Use Connection Pooling. -
Create a session, a queue named
MyQueue
, and a message consumer.// Create a session. final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create a queue named "MyQueue". final Destination consumerDestination = consumerSession.createQueue("MyQueue"); // Create a message consumer from the session to the queue. final MessageConsumer consumer = consumerSession.createConsumer(consumerDestination);
-
Begin to wait for messages and receive the message when it arrives.
// Begin to wait for messages. final Message consumerMessage = consumer.receive(1000); // Receive the message when it arrives. final TextMessage consumerTextMessage = (TextMessage) consumerMessage; System.out.println("Message received: " + consumerTextMessage.getText());
Note
Unlike AWS messaging services (such as Amazon SQS), the consumer is constantly connected to the broker.
-
Close the consumer, session, and connection.
consumer.close(); consumerSession.close(); consumerConnection.close();
Step 3: (Optional) Connect to an AWS Lambda function
AWS Lambda can connect to and consume messages from your Amazon MQ broker. When you connect a broker to Lambda, you create an event source mapping that reads messages from a queue and invokes the function synchronously. The event source mapping you create reads messages from your broker in batches and converts them into a Lambda payload in the form of a JSON object.
To connect your broker to a Lambda function
-
Add the following IAM role permissions to your Lambda function execution role.
Note
Without the necessary IAM permissions, your function will not be able to successfully read records from Amazon MQ resources.
-
(Optional) If you have created a broker without public accessibility, you must do one of the following to allow Lambda to connect to your broker:
-
Configure one NAT gateway per public subnet. For more information, see Internet and service access for VPC-connected functions in the AWS Lambda Developer Guide.
-
Create a connection between your Amazon Virtual Private Cloud (Amazon VPC) and Lambda using a VPC endpoint. Your Amazon VPC must also connect to AWS Security Token Service (AWS STS) and Secrets Manager endpoints. For more information, see Configuring interface VPC endpoints for Lambda in the AWS Lambda Developer Guide.
-
-
Configure your broker as an event source for a Lambda function using the AWS Management Console. You can also use the
create-event-source-mapping
AWS Command Line Interface command. -
Write some code for your Lambda function to process the messages consumed from your broker. The Lambda payload that retrieved by your event source mapping depends on the engine type of the broker. The following is an example of a Lambda payload for an Amazon MQ for ActiveMQ queue.
Note
In the example,
testQueue
is the name of the queue.{ "eventSource": "aws:amq", "eventSourceArn": "arn:aws:mq:us-west-2:112556298976:broker:test:b-9bcfa592-423a-4942-879d-eb284b418fc8", "messages": { [ { "messageID": "ID:b-9bcfa592-423a-4942-879d-eb284b418fc8-1---mq---us-west-2.amazonaws.com.rproxy.goskope.com-37557-1234520418293-4:1:1:1:1", "messageType": "jms/text-message", "data": "QUJDOkFBQUE=", "connectionId": "myJMSCoID", "redelivered": false, "destination": { "physicalname": "testQueue" }, "timestamp": 1598827811958, "brokerInTime": 1598827811958, "brokerOutTime": 1598827811959 }, { "messageID": "ID:b-9bcfa592-423a-4942-879d-eb284b418fc8-1---mq---us-west-2.amazonaws.com.rproxy.goskope.com-37557-1234520418293-4:1:1:1:1", "messageType":"jms/bytes-message", "data": "3DTOOW7crj51prgVLQaGQ82S48k=", "connectionId": "myJMSCoID1", "persistent": false, "destination": { "physicalname": "testQueue" }, "timestamp": 1598827811958, "brokerInTime": 1598827811958, "brokerOutTime": 1598827811959 } ] } }
For more information about connecting Amazon MQ to Lambda, the options Lambda supports for an Amazon MQ event source, and event source mapping errors, see Using Lambda with Amazon MQ in the AWS Lambda Developer Guide.