一、简单的RabbitMQ示例

  • 生产者
  1. # Author:Li Dongfei
  2. import pika
  3. connection = pika.BlockingConnection(
  4. pika.ConnectionParameters('localhost')
  5. ) #建立一个连接
  6. channel = connection.channel() #声明一个管道
  7. channel.queue_declare(queue='hello') #生成一个queue
  8. channel.basic_publish(exchange='',
  9. routing_key='hello', #queue名字
  10. body='Hello World!')
  11. print(" [x] Sent 'Hello World!'")
  12. connection.close()
  • 消费者
  1. # Author:Li Dongfei
  2. import pika
  3. connection = pika.BlockingConnection(
  4. pika.ConnectionParameters('localhost')
  5. )
  6. channel = connection.channel()
  7. channel.queue_declare(queue='hello')
  8. def callback(ch, method, properties, body):
  9. print("-->", ch, method, properties)
  10. print(" [x] Received %r" %body)
  11. channel.basic_consume(callback, #开始消费消息,如果收到消息就调用callback函数来处理消息
  12. queue='hello',
  13. no_ack=True
  14. )
  15. print(' [*] Waiting for messages. To exit press CTRL+C')
  16. channel.start_consuming() #开始收消息

二、RabbitMQ命令行工具

  1. C:\>cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin
  2. C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin>rabbitmqctl.bat list_queues #列出当前的queue

三、rabbitmq持久化

  • 队列持久化
  1. channel.queue_declare(queue='hello', durable=True) #durable=True声明队列持久化
  • 消息持久化
  1. channel.basic_publish(exchange='',
  2. routing_key='hello', #queue名字
  3. body='Hello World!',
  4. properties=pika.BasicProperties(
  5. delivery_mode=2 #消息持久化
  6. ))

四、消息调度

  • 在消费者中定义
  1. channel.basic_qos(prefetch_count=1) #只要当前有一条消息在处理则不要给我发消息

五、广播模式

  • fanout:所有bind到此exchange的queue都可以接受消息
  • 订阅/发布
    生成者
  1. # Author:Li Dongfei
  2. import pika
  3. connection = pika.BlockingConnection(
  4. pika.ConnectionParameters('localhost')
  5. )
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='logs',
  8. exchange_type='fanout')
  9. message = "info: Hello World!"
  10. channel.basic_publish(exchange='logs',
  11. routing_key='',
  12. body=message)
  13. print(" [x] Sent %r" %message)
  14. connection.close()

消费者

  1. # Author:Li Dongfei
  2. import pika
  3. connection = pika.BlockingConnection(
  4. pika.ConnectionParameters('localhost')
  5. )
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='logs',
  8. exchange_type='fanout')
  9. result = channel.queue_declare(exclusive=True) #exclusive 唯一的
  10. queue_name = result.method.queue
  11. channel.queue_bind(exchange='logs',
  12. queue=queue_name)
  13. print(' [*] Waiting for logs. To exit press CTRL+C')
  14. def callback(ch, method, properties, body):
  15. print(" [x] %r" %body)
  16. channel.basic_consume(callback,
  17. queue=queue_name,
  18. no_ack=True)
  19. channel.start_consuming()
  • direct:通过routingKey和exchange决定的哪个唯一的queue可以接受消息
    生产者
  1. # Author:Li Dongfei
  2. import pika, sys
  3. connection = pika.BlockingConnection(pika.ConnectionParameters(
  4. host='localhost'
  5. ))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='direct_logs',
  8. exchange_type='direct')
  9. serverity = sys.argv[1] if len(sys.argv) > 1 else 'info'
  10. message = ' '.join(sys.argv[2:]) or 'Hello World!'
  11. channel.basic_publish(exchange='direct_logs',
  12. routing_key=serverity,
  13. body=message)
  14. print(" [x] Sent %r:%r" %(serverity, message))
  15. connection.close()

消费者

  1. # Author:Li Dongfei
  2. import pika, sys
  3. connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
  4. channel = connection.channel()
  5. channel.exchange_declare(exchange='direct_logs',
  6. exchange_type='direct')
  7. result = channel.queue_declare(exclusive=True)
  8. queue_name = result.method.queue
  9. serverities = sys.argv[1:]
  10. if not serverities:
  11. sys.stderr.write("Usage: %s [info] [warning] [error]\n" %sys.argv[0])
  12. sys.exit(1)
  13. for serverity in serverities:
  14. channel.queue_bind(exchange='direct_logs',
  15. queue=queue_name,
  16. routing_key=serverity)
  17. print(' [*] Wating for logs. To exit press CTRL+C')
  18. def callback(ch, method, properties, body):
  19. print(" [x] %r:%r" %(method.routing_key, body))
  20. channel.basic_consume(callback,
  21. queue=queue_name,
  22. no_ack=True)
  23. channel.start_consuming()
  • topic:所有符合routingKey的routingKey所bind的queue可以接受消息

    六、rabbitMQ rpc

  • client
  1. # Author:Li Dongfei
  2. import pika, uuid
  3. class FibonacciTpcClient(object):
  4. def __init__(self):
  5. self.connection = pika.BlockingConnection(pika.ConnectionParameters(
  6. host='localhost'
  7. ))
  8. self.channel = self.connection.channel()
  9. result = self.channel.queue_declare(exclusive=True)
  10. self.callback_queue = result.method.queue
  11. self.channel.basic_consume(self.on_response, no_ack=True,
  12. queue=self.callback_queue)
  13. def on_response(self, ch, method, props, body):
  14. if self.corr_id == props.correlation_id:
  15. self.response = body
  16. def call(self, n):
  17. self.response = None
  18. self.corr_id = str(uuid.uuid4())
  19. self.channel.basic_publish(exchange='',
  20. routing_key='rpc_queue',
  21. properties=pika.BasicProperties(
  22. reply_to=self.callback_queue,
  23. correlation_id=self.corr_id,
  24. ),
  25. body=str(n))
  26. while self.response is None:
  27. self.connection.process_data_events()
  28. return int(self.response)
  29. fibonacci_rpc = FibonacciTpcClient()
  30. print(" [x] Requesting fib(30)")
  31. response = fibonacci_rpc.call(30)
  32. print(" [.] Got %r" %response)
  • server
  1. # Author:Li Dongfei
  2. import pika, time
  3. connection = pika.BlockingConnection(pika.ConnectionParameters(
  4. host='localhost'
  5. ))
  6. channel = connection.channel()
  7. channel.queue_declare(queue='rpc_queue')
  8. def fib(n):
  9. if n == 0:
  10. return 0
  11. elif n == 1:
  12. return 1
  13. else:
  14. return fib(n-1) + fib(n-2)
  15. def on_request(ch, method, props, body):
  16. n = int(body)
  17. print(" [.] fib(%s)" %n)
  18. response = fib(n)
  19. ch.basic_publish(exchange='',
  20. routing_key=props.reply_to,
  21. properties=pika.BasicProperties(correlation_id=props.correlation_id),
  22. body=str(response))
  23. ch.basic_ack(delivery_tag=method.delivery_tag)
  24. channel.basic_qos(prefetch_count=1)
  25. channel.basic_consume(on_request, queue='rpc_queue')
  26. print(" [x] Awatiing RPC requests")
  27. channel.start_consuming()

190225RabbitMQ的更多相关文章

随机推荐

  1. PHP框架 Laravel

    PHP框架 CI(CodeIgniter) http://www.codeigniter.com/ http://codeigniter.org.cn/ Laravel PHP Laravel htt ...

  2. 用sysbench压测MySQL,通过orzdba监控MySQL

    1.1 安装sysbench wget https://codeload.github.com/akopytov/sysbench/zip/0.5 unzip 0.5 cd sysbench-0.5/ ...

  3. ssh免密连接远程服务器

    ssh免密连接远程服务器 借助ssky-keygen和ssh-copy-id工具,通过4个简单的步骤实现无需输入密码登录远程Linux主机 1 生成密钥 通过内置的工具生成RSA算法加密的密钥 ssh ...

  4. OSCache安装

    OSCache是一个基于web应用的组件,他的安装工作主要是对web应用进行配置,大概的步骤如下: 1. 下载.解压缩OSCachehttps://java.net/downloads/oscache ...

  5. 对象序列化中transient关键字的用途

  6. xcode中的预定义宏

    [xcode中的预定义宏] 1.SRCROOT,是定义本target的proj的路径. 2.OBJROOT,对象文件根路径,对象文件(即obj文件)就是中间的临时文件.中间文件输出目录的名字以“pro ...

  7. laravel 验证表单信息

    1控制器验证 $this->validate($request,[ 'Student.name'=>'required|min:2|max:20', 'Student.age'=>' ...

  8. 使用Layered Window遇到的一些问题及解决方法

    1. 使用Layered Window需要设置 WS_EX_LAYERED 属性 2.  Layered Window不能作为Child Window 3. 它也不能包含子窗口,为什么呢,因为它收不到 ...

  9. 基于jquery 的插件,让IE支持placeholder属性

    开发一个项目的时候为了美观和用户体验用到了input标签的placeholder属性,但是这个属性是html5中的,所以低版本的IE浏览器不支持.于是在百度找了一些解决方法,找了好几个都不是那么完美, ...

  10. ubuntu16.04 安装openpose

    安装 Anaconda3 Tensorflow-cpu python3tensorflow 1.4.1+opencv3, protobuf, python3-tk ================== ...