Python使用示例

send message

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

receive message

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

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

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

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

详情见官方文档:http://www.rabbitmq.com/tutorials/tutorial-one-python.html

 

Java/PHP/Ruby/C#

详情见官方文档:http://www.rabbitmq.com/tutorials/tutorial-one-java.html 

PHP使用示例

详情见官方文档:http://www.rabbitmq.com/tutorials/tutorial-one-php.html

Ruby使用示例

详情见官方文档:http://www.rabbitmq.com/tutorials/tutorial-one-ruby.html

C#使用示例

详情见官方文档:http://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html

MQTT协议使用示例

示例代码

#!/usr/bin/env python
# encoding: utf-8
#导入mosquitto的python库

#import mosquitto
import paho.mqtt.client as paho

# 定义自己的callback 函数

def on_connect(mosq, obj, rc):
   mosq.subscribe("$SYS/#", 0)
   print("rc: "+str(rc))

def on_message(mosq, obj, msg):
   print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

def on_publish(mosq, obj, mid):
   print("mid: "+str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
   print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mosq, obj, level, string):
   print(string)

# 创建客户端
# If you want to use a specific client id, use
# mqttc = mosquitto.Mosquitto("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
#mqttc = mosquitto.Mosquitto()
mqttc = paho.Client()

# 注册callback函数
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log

# 连接服务器
#mqttc.connect("test.mosquitto.org", 1883, 60)
mqttc.connect("172.17.0.2", 1883, 60)

# 订阅消息
mqttc.subscribe("string", 0)
#mqttc.subscribe(("tuple", 1))
#mqttc.subscribe([("list0", 0), ("list1", 1)])

# 无限循环处理
mqttc.loop_forever()