text: #!/usr/bin/env python3
  # -*- coding:utf-8 -*-
  # author: bigfoolliu
  
  
  """
  pika模块
  
  python操作RabbitMQ详解：https://www.cnblogs.com/shenh/p/10497244.html
  python操作RabbitMQ：https://segmentfault.com/a/1190000017277218
  
  - producer产生消息
  """
  
  import json
  import pika
  
  
  def set_connection():
      """设置连接"""
      # mq的用户名和密码
      print('开始设置连接')
      credential = pika.PlainCredentials('root', 'root')
      
      # 设置连接
      host = "localhost"
      connection = pika.BlockingConnection(
          pika.ConnectionParameters(host=host, port=5672, virtual_host="/", credentials=credential))
  
      print(f'设置连接{connection}完成')
      return connection
  
  
  def set_channel(connection):
      """开启信道，申明交换器"""
      # 声明交换器，消息将在这个交换器中传递，如果不存在将创建
      print('开始申明消息队列')
      channel = connection.channel()
      result = channel.queue_declare(queue="python_test", passive=False, durable=False, exclusive=False, auto_delete=False)
      print(f'消息队列{channel}申明完成')
      return channel
      
  
  def insert_value(channel):
      """向队列中插入数值"""
      # 想队列中插入数值,routing_key是队列名字
      print('开始向队列中插入消息')
      for i in range(10):
          message = json.dumps({"OrderId": "1000%s" % i})
          channel.basic_publish(exchange="", routing_key="python_test", body=message)
          print(message)
      print('消息插入完毕')
  
  
  def close_connection(connection):
      print('断开连接')
      connection.close()
      print(f'断开连接{connection}完毕')
  
  
  def main():
      conn = set_connection()
      chn = set_channel(conn)
      insert_value(chn)
      close_connection(conn)
  
  
  if __name__ == "__main__":
      main()
  
  