Last updated 3rd June 2021
Objective
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
Grid |
---|
3.5 |
3.6 |
3.7 |
3.8 |
Relationship
The format exposed in the $PLATFORM_RELATIONSHIPS
environment variable:
{
"username": "guest",
"scheme": "amqp",
"service": "rabbitmq38",
"fragment": null,
"ip": "169.254.232.78",
"hostname": "iwrccysk3gpam2zdlwdr5fgs2y.rabbitmq38.service._.eu-3.platformsh.site",
"public": false,
"cluster": "rjify4yjcwxaa-master-7rqtwti",
"host": "rabbitmq.internal",
"rel": "rabbitmq",
"query": [],
"path": null,
"password": "guest",
"type": "rabbitmq:3.8",
"port": 5672,
"host_mapped": false
}
Usage example
In your .platform/services.yaml
:
queuerabbit:
type: rabbitmq:3.8
disk: 512
The minimum disk size for RabbitMQ is 512
(MB).
In your .platform.app.yaml
:
relationships:
rabbitmqqueue: "queuerabbit:rabbitmq"
You will need to use
rabbitmq
type when defining the service```yaml
.platform/services.yaml
service_name: type: rabbitmq:version disk: 512 ```
and the endpoint
rabbitmq
when defining the relationship```yaml
.platform.app.yaml
relationships: relationship_name: “service_name:rabbitmq” ```
Your
service_name
andrelationship_name
are defined by you, but we recommend making them distinct from each other.
You can then use the service in a configuration file of your application with something like:
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 Web PaaS 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 Web PaaS 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("Web PaaS");
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 Web PaaS 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 Web PaaS 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:rabbitmqqueue.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:rabbitmqqueue.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:rabbitmqqueue.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.
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
Did you find this guide useful?
Please feel free to give any suggestions in order to improve this documentation.
Whether your feedback is about images, content, or structure, please share it, so that we can improve it together.
Your support requests will not be processed via this form. To do this, please use the "Create a ticket" form.
Thank you. Your feedback has been received.