RabbitMQ (Message queue service)

RabbitMQ is an open source message broker software (sometimes called message-oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP).

See the RabbitMQ documentation for more information.

Use a framework 

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

For more implementation ideas, consult a template.

Supported versions 

Grid Dedicated Gen 3 Dedicated Gen 2
  • 3.11
  • 3.10
  • 3.9
  • 3.9 BETA
  • 3.9

The following versions aren’t available in the EU-1 and US-1 regions:

  • 3.11

  • 3.10

  • 3.9

Consider region migration if your project is in those regions.

Relationship 

The format exposed in the $PLATFORM_RELATIONSHIPS environment variable:

{
    "username": "guest",
    "scheme": "amqp",
    "service": "rabbitmq38",
    "fragment": null,
    "ip": "169.254.57.5",
    "hostname": "iwrccysk3gpam2zdlwdr5fgs2y.rabbitmq38.service._.eu-3.platformsh.site",
    "port": 5672,
    "cluster": "rjify4yjcwxaa-master-7rqtwti",
    "host": "rabbitmq.internal",
    "rel": "rabbitmq",
    "path": null,
    "query": [],
    "password": "guest",
    "type": "rabbitmq:3.8",
    "public": false,
    "host_mapped": false
}

Usage example 

1. Configure the service 

To define the service, use the rabbitmq type:

.platform/services.yaml
<SERVICE_NAME>:
    type: rabbitmq:<VERSION>
    disk: 512

Note that if you later change the name, it’s treated as an entirely new service. This removes all data from your service. Always backup your data before changing the service.

2. Add the relationship 

To define the relationship, use the rabbitmq endpoint :

.platform.app.yaml
relationships:
    <RELATIONSHIP_NAME>: "<SERVICE_NAME>:rabbitmq"

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, but it’s best if they’re distinct.

Example Configuration 

Service definition

.platform/services.yaml
queuerabbit:
    type: rabbitmq:3.11
    disk: 512

App configuration

.platform.app.yaml
relationships:
    rabbitmqqueue: "queuerabbit:rabbitmq"

Use in app 

Then use the service in your app with a configuration file like the following:

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

(The specific way to inject configuration into your application varies. Consult your application or framework’s documentation.)

Connecting to RabbitMQ 

From your local development environment 

For debugging purposes, it’s sometimes useful to connect directly to a service with an SSH tunnel. Open a tunnel with port forwarding:

platform tunnel:single -g

Then launch a RabbitMQ client of your choice configured to connect to the location returned.

Access the management plugin (Web UI) 

To access the browser-based UI, use an SSH tunnel. To open a tunnel, follow these steps.

  1. SSH into your app container with a flag for local port forwarding:

    ssh $(platform ssh --pipe) -L 15672:<RELATIONSHIP_NAME>.internal:15672
  2. Within that SSH session, get the username and password. Use the following command to see your app’s relationships:

    echo "$PLATFORM_RELATIONSHIPS" | base64 --decode | jq .
  3. Open http://localhost:15672 in your browser. Use the credentials from step 2.

From the application container 

The application container currently doesn’t include any useful utilities to connect to RabbitMQ with. However, you can install your own by adding a client as a dependency in your .platform.app.yaml file.

For example, you can use amqp-utils by adding this:

dependencies:
   ruby:
       amqp-utils: "0.5.1"

Then, when you SSH into your container, you can type any amqp- command available to manage your queues.

Configuration 

Virtual hosts 

You can configure additional virtual hosts to a RabbitMQ service, which can be useful for separating resources, such as exchanges, queues, and bindings, to their own namespace. In your .platform/services.yaml file define the names of the virtual hosts under the configuration.vhosts attribute:

rabbitmq:
    type: rabbitmq:3.8
    disk: 512
    configuration:
        vhosts:
            - foo
            - bar