Platform.sh User Documentation

RabbitMQ (message queue service)

Try for 30 days
Flexible, version-controlled infrastructure provisioning and development-to-production workflows
Activate your trial

RabbitMQ is a message broker that supports multiple messaging protocols, such as the Advanced Message Queuing Protocol (AMQP). It gives your apps a common platform to send and receive messages and your messages a safe place to live until they’re received.

Use a framework Anchor to this heading

If you use one of the following frameworks, follow its guide:

Supported versions Anchor to this heading

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.

Grid Dedicated Gen 3 Dedicated Gen 2
  • 3.13
  • 3.12
  • 3.13
  • 3.12
  • 3.13
  • 3.12

Deprecated versions Anchor to this heading

The following versions are deprecated. They’re available, but they aren’t receiving security updates from upstream and aren’t guaranteed to work. They’ll be removed in the future, so migrate to one of the supported versions.

Grid Dedicated Gen 3 Dedicated Gen 2
  • 3.11
  • 3.10
  • 3.9
  • 3.8
  • 3.7
  • 3.6
  • 3.5
  • 3.11
  • 3.10
  • 3.9
  • 3.11
  • 3.10
  • 3.9
  • 3.8
  • 3.7

Relationship reference Anchor to this heading

Example information available through the PLATFORM_RELATIONSHIPS environment variable or by running platform relationships.

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the PLATFORM_RELATIONSHIPS environment variable directly rather than hard coding any values.

{
  "username": "guest",
  "scheme": "amqp",
  "service": "rabbitmq",
  "fragment": null,
  "ip": "123.456.78.90",
  "hostname": "azertyuiopqsdfghjklm.rabbitmq.service._.eu-1.platformsh.site",
  "port": 5672,
  "cluster": "azertyuiopqsdf-main-afdwftq",
  "host": "rabbitmq.internal",
  "rel": "rabbitmq",
  "path": null,
  "query": [],
  "password": "ChangeMe",
  "type": "rabbitmq:3.13",
  "public": false,
  "host_mapped": false
}

Usage example Anchor to this heading

1. Configure the service Anchor to this heading

To define the service, use the rabbitmq type:

.platform/services.yaml
# The name of the service container. Must be unique within a project.
<SERVICE_NAME>:
  type: rabbitmq:<VERSION>
  disk: 512

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

2. Define the relationship Anchor to this heading

To define the relationship, use the following configuration:

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
  <SERVICE_NAME>:

You can define <SERVICE_NAME> as you like, so long as it’s unique between all defined services and matches in both the application and services configuration.

The example above leverages default endpoint configuration for relationships. That is, it uses default endpoints behind-the-scenes, providing a relationship (the network address a service is accessible from) that is identical to the name of that service.

Depending on your needs, instead of default endpoint configuration, you can use explicit endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <SERVICE_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows configuration with an explicitly set service name and endpoint.
# See the Application reference for all options for defining relationships and endpoints.
# Note that legacy definition of the relationship is still supported.
# More information: https://docs.platform.sh/create-apps/app-reference/single-runtime-image.html#relationships
relationships:
  <RELATIONSHIP_NAME>:
    service: <SERVICE_NAME>
    endpoint: rabbitmq

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, so long as it’s unique between all defined services and relationships and matches in both the application and services configuration.

The example above leverages explicit endpoint configuration for relationships.

Depending on your needs, instead of explicit endpoint configuration, you can use default endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <RELATIONSHIP_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

Example configuration Anchor to this heading

Service definition Anchor to this heading

.platform/services.yaml
# The name of the service container. Must be unique within a project.
rabbitmq:
  type: rabbitmq:3.13
  disk: 512

App configuration Anchor to this heading

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
  rabbitmq:
.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows configuration with an explicitly set service name and endpoint.
# See the Application reference for all options for defining relationships and endpoints.
# Note that legacy definition of the relationship is still supported.
# More information: https://docs.platform.sh/create-apps/app-reference/single-runtime-image.html#relationships
relationships:
  rabbitmq:
    service: rabbitmq
    endpoint: rabbitmq

Use in app Anchor to this heading

To use the configured service in your app, add a configuration file similar to the following to your project.

package examples

import (
	"fmt"
	psh "github.com/platformsh/config-reader-go/v2"
	amqpPsh "github.com/platformsh/config-reader-go/v2/amqp"
	"github.com/streadway/amqp"
	"sync"
)

func UsageExampleRabbitMQ() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to RabbitMQ.
	credentials, err := config.Credentials("rabbitmq")
	checkErr(err)

	// Use the amqp formatted credentials package.
	formatted, err := amqpPsh.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to the RabbitMQ server.
	connection, err := amqp.Dial(formatted)
	checkErr(err)
	defer connection.Close()

	// Make a channel.
	channel, err := connection.Channel()
	checkErr(err)
	defer channel.Close()

	// Create a queue.
	q, err := channel.QueueDeclare(
		"deploy_days", // name
		false,         // durable
		false,         // delete when unused
		false,         // exclusive
		false,         // no-wait
		nil,           // arguments
	)

	body := "Friday"
	msg := fmt.Sprintf("Deploying on %s", body)

	// Publish a message.
	err = channel.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(msg),
		})
	checkErr(err)

	outputMSG := fmt.Sprintf("[x] Sent '%s' <br>", body)

	// Consume the message.
	msgs, err := channel.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	checkErr(err)

	var received string
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		for d := range msgs {
			received = fmt.Sprintf("[x] Received message: '%s' <br>", d.Body)
			wg.Done()
		}
	}()

	wg.Wait()

	outputMSG += received

	return outputMSG
}
package sh.platform.languages.sample;

import sh.platform.config.Config;
import sh.platform.config.RabbitMQ;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.function.Supplier;

public class RabbitMQSample implements Supplier<String> {

    @Override
    public String get() {
        StringBuilder logger = new StringBuilder();

        // Create a new config object to ease reading the Platform.sh environment variables.
        // You can alternatively use getenv() yourself.
        Config config = new Config();
        try {
            // Get the credentials to connect to the RabbitMQ service.
            final RabbitMQ credential = config.getCredential("rabbitmq", RabbitMQ::new);
            final ConnectionFactory connectionFactory = credential.get();

            // Connect to the RabbitMQ server.
            final Connection connection = connectionFactory.createConnection();
            connection.start();
            final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("cloud");
            MessageConsumer consumer = session.createConsumer(queue);

            // Sending a message into the queue.
            TextMessage textMessage = session.createTextMessage("Platform.sh");
            textMessage.setJMSReplyTo(queue);
            MessageProducer producer = session.createProducer(queue);
            producer.send(textMessage);

            // Receive the message.
            TextMessage replyMsg = (TextMessage) consumer.receive(100);

            logger.append("<p>");
            logger.append("Message: ").append(replyMsg.getText());
            logger.append("</p>");

            // close connections.
            producer.close();
            consumer.close();
            session.close();
            connection.close();
            return logger.toString();
        } catch (Exception exp) {
            throw new RuntimeException("An error when execute RabbitMQ", exp);
        }
    }
}
<?php

declare(strict_types=1);

use Platformsh\ConfigReader\Config;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();

// Get the credentials to connect to the RabbitMQ service.
$credentials = $config->credentials('rabbitmq');

try {

    $queueName = 'deploy_days';

    // Connect to the RabbitMQ server.
    $connection = new AMQPStreamConnection($credentials['host'], $credentials['port'], $credentials['username'], $credentials['password']);
    $channel = $connection->channel();

    $channel->queue_declare($queueName, false, false, false, false);

    $msg = new AMQPMessage('Friday');
    $channel->basic_publish($msg, '', 'hello');

    echo "[x] Sent 'Friday'<br/>\n";

    // In a real application you't put the following in a separate script in a loop.
    $callback = function ($msg) {
        printf("[x] Deploying on %s<br />\n", $msg->body);
    };

    $channel->basic_consume($queueName, '', false, true, false, false, $callback);

    // This blocks on waiting for an item from the queue, so comment it out in this demo script.
    //$channel->wait();

    $channel->close();
    $connection->close();

} catch (Exception $e) {
    print $e->getMessage();
}

import pika
from platformshconfig import Config


def usage_example():
    # Create a new Config object to ease reading the Platform.sh environment variables.
    # You can alternatively use os.environ yourself.
    config = Config()

    # Get the credentials to connect to the RabbitMQ service.
    credentials = config.credentials('rabbitmq')

    try:
        # Connect to the RabbitMQ server
        creds = pika.PlainCredentials(credentials['username'], credentials['password'])
        parameters = pika.ConnectionParameters(credentials['host'], credentials['port'], credentials=creds)

        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()

        # Check to make sure that the recipient queue exists
        channel.queue_declare(queue='deploy_days')

        # Try sending a message over the channel
        channel.basic_publish(exchange='',
                              routing_key='deploy_days',
                              body='Friday!')

        # Receive the message
        def callback(ch, method, properties, body):
            print(" [x] Received {}".format(body))

        # Tell RabbitMQ that this particular function should receive messages from our 'hello' queue
        channel.basic_consume('deploy_days',
                              callback,
                              auto_ack=False)

        # This blocks on waiting for an item from the queue, so comment it out in this demo script.
        # print(' [*] Waiting for messages. To exit press CTRL+C')
        # channel.start_consuming()

        connection.close()

        return " [x] Sent 'Friday!'<br/>"

    except Exception as e:
        return e

Connect to RabbitMQ Anchor to this heading

When debugging, you may want to connect directly to your RabbitMQ service. You can connect in multiple ways:

In each case, you need the login credentials that you can obtain from the relationship.

Via SSH Anchor to this heading

To connect directly to your RabbitMQ service in an environment, open an SSH tunnel with the Platform.sh CLI.

To open an SSH tunnel to your service with port forwarding, run the following command:

platform tunnel:single --gateway-ports

Then configure a RabbitMQ client to connect to this tunnel using the credentials from the relationship. See a list of RabbitMQ client libraries.

Access the management UI Anchor to this heading

RabbitMQ offers a management plugin with a browser-based UI. You can access this UI with an SSH tunnel.

To open a tunnel, follow these steps.

  1. a) (On grid environments) SSH into your app container with a flag for local port forwarding:

    ssh $(platform ssh --pipe) -L 15672:RELATIONSHIP_NAME.internal:15672

    RELATIONSHIP_NAME is the name you defined.

    b) (On dedicated environments) SSH into your cluster with a flag for local port forwarding:

    ssh $(platform ssh --pipe) -L 15672:localhost:15672
  2. Open http://localhost:15672 in your browser. Log in using the username and password from the relationship.

Configuration options Anchor to this heading

You can configure your RabbitMQ service in the services configuration with the following options:

Name Type Required Description
vhosts List of strings No Virtual hosts used for logically grouping resources.

You can configure additional virtual hosts, which can be useful for separating resources, such as exchanges, queues, and bindings, into their own namespaces. To create virtual hosts, add them to your configuration as in the following example:

.platform/services.yaml
# The name of the service container. Must be unique within a project.
rabbitmq:
  type: "rabbitmq:3.13"
  disk: 512
  configuration:
    vhosts:
      - host1
      - host2

Upgrading Anchor to this heading

When upgrading RabbitMQ, skipping major versions (e.g. 3.7 -> 3.11) is not supported. Make sure you upgrade sequentially (3.7 -> 3.8 -> 3.9 -> 3.10 -> 3.11) and that each upgrade commit translates into an actual deployment.

Is this page helpful?