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.

Supported versions

  • 3.5
  • 3.6
  • 3.7

Relationship

The format exposed in the $PLATFORM_RELATIONSHIPS environment variable:

{
    "username": "guest",
    "scheme": "amqp",
    "service": "rabbitmq",
    "ip": "169.254.178.95",
    "hostname": "qmx5lbdjoolco7dqjr7cx26r7q.rabbitmq.service._.eu-3.platformsh.site",
    "cluster": "rjify4yjcwxaa-master-7rqtwti",
    "host": "rabbitmq.internal",
    "rel": "rabbitmq",
    "password": "guest",
    "type": "rabbitmq:3.7",
    "port": 5672
}

Usage example

In your .platform/services.yaml:

queuerabbit:
    type: rabbitmq:3.7
    disk: 256

In your .platform.app.yaml:

relationships:
    rabbitmqqueue: "queuerabbit:rabbitmq"

You can then use the service in a configuration file of your application with something like:

Go
Java
PHP
Python
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("Message: ").append(replyMsg.getText());

            // 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 will vary. Consult your application or framework's documentation.)

Connecting to RabbitMQ

From your local development environment

For debugging purposes, it's sometimes useful to be able to directly connect to a service instance. You can do this using SSH tunneling. To open a tunnel, log into your application container like usual, but with an extra flag to enable local port forwarding:

ssh -L 5672:mq.internal:5672 <projectid>-<branch_ID>@ssh.eu.platform.sh

Within that SSH session, use the following command to pretty-print your relationships. This lets you see which username and password to use, and you can double check that the remote service's port is 5672.

php -r 'print_r(json_decode(base64_decode($_ENV["PLATFORM_RELATIONSHIPS"])));'

If your service is running on a different port, you can re-open your SSH session with the correct port by modifying your -L flag: -L 5672:mq.internal:<remote port>.

Finally, while the session is open, you can launch a RabbitMQ client of your choice from your local workstation, configured to connect to localhost:5672 using the username and password you found in the relationship variable.

Access the management plugin (Web UI)

In case you want to access the browser-based UI, you have to use an SSH tunnel. To open a tunnel, log into your application container like usual, but with an extra flag to enable local port forwarding:

ssh -L 15672:mq.internal:15672 <projectid>-<branch_ID>@ssh.eu.platform.sh

After you successfully established a connection, you should be able to open http://localhost:15672 in your browser. You'll find the credentials like mentioned above.

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 simply type any amqp- command available to manage your queues.