Thursday, June 23, 2016

rabbitmq basic -- message broker

RabbitMQ works as a message broker. it simply accepts and forwards messages between sender and recipient. 

1- install rabbitmq package on ubuntu
$ sudo apt-get install rabbitmq-server

2- start rabbitmq service
$ sudo /etc/init.d/rabbitmq-server start

3- enable management plugin that problem webui and you can manage and monitor rabbitmq service
$ rabbitmq-plugins enable rabbitmq_management

4- create administrator users and set tags to  management in order it to login to webui to monitor messages
$ rabbitmqctl add_user newadmin newadmin
$ rabbitmqctl  set_permissions -p / newadmin ".*" ".*" ".*"
$ rabbitmqctl set_user_tags newadmin  management policymaker monitoring administrator

*** note ***
there are 4 tags: management, policymaker, monitoring, administrator.
consult this document to see what each tag can do https://www.rabbitmq.com/management.html

now we can not login to web ui to manage and monitor it, using url http://localhost:15672/ with username/password newadmin/newadmin

-- web interface to manage user vhost and policy


5- example to create a virtual host with userv to manage it using command line. we are also be able to create with gui, because now we can access the webui
$ rabbitmqctl add_vhosts userv
$ rabbitmqctl add_vhost userv
$ rabbitmqctl add_user userv userv
$ rabbitmqctl set_permissions -p userv  userv ".*" ".*" ".*"


6- command to lists users and vhosts
$ rabbitmqctl list_users
Listing users ...
guest    [administrator]
newadmin    [management, policymaker, monitoring, administrator]
userv    []


$ rabbitmqctl list_vhosts
Listing vhosts ...
/
userv



------------------------------------
script to send message to server "send.py"

#!/usr/bin/env python
import pika
import sys

qchannel = sys.argv[1]
qmessage = sys.argv[2]
connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))
channel = connection.channel()
channel.queue_declare(queue=qchannel)
channel.basic_publish(exchange='',
                      routing_key=qchannel,
                      body=qmessage)
print(" [x] Sent ")


script to receive message

#!/usr/bin/env python
import pika
import sys

qname = sys.argv[1]
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue=qname)

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue=qname,
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()




1- to send message using queue name hello
$ python send.py hello "my first message"

2- to receive message from queue name hello
$ python receive.py hello

- message rate graph when send/receive message

No comments:

Post a Comment