设为首页 收藏本站
查看: 564|回复: 0

[经验分享] Python 12nd Day

[复制链接]

尚未签到

发表于 2017-7-2 12:09:25 | 显示全部楼层 |阅读模式
Rabbitmq

Hello World!
  sending:
  1) establish connection



#!/usr/bin/env python
import pika
# establish a connection with RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
  2) create a queue to which the message will be delivered



channel.queue_declare(queue='hello')
  In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
  We use a default exchange identified by an empty string, it allows us to specify exactly to which queue the message should go. The queue name needs to be specified in the routing_key parameter:
  3) sending



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



connection.close()
  Receving:
  1) connect to RabbitMQ server. The code responsible for connecting to Rabbit is the same as previously



#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
  2) make sure that the queue exists. Creating a queue using queue_declare is idempotent (幂等) ‒ we can run the command as many times as we like, and only one will be created



channel.queue_declare(queue='hello')
  You may ask why we declare the queue again ‒ we have already declared it in our previous code. We could avoid that if we were sure that the queue already exists. For example if send.py program was run before. But we're not yet sure which program to run first. In such cases it's a good practice to repeat declaring the queue in both programs (sending & receving).
  3) Receiving messages from the queue works by subscribing a callback function to a queue. Whenever we receive a message, this callback function is called by the Pika library.



# deal with received messages
def callback(ch, method, properties, body):
    # print on the screen the contents of the message
print(" [x] Received %r" % body)
  4) tell RabbitMQ that this particular callback function should receive messages from our hello queue



channel.basic_consume(callback,
queue='hello',
no_ack=True)
  5) enter a never-ending loop that waits for data and runs callbacks whenever necessary



print('
  • Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
    publish/subscribe
      1) Exchange
      There are a few exchange types available: direct, topic, headers and fanout. We'll focus on the last one -- the fanout. it just broadcasts all the messages it receives to all the queues it knows.



    # create an exchange of fanout type
    channel.exchange_declare(exchange='logs',
    type='fanout')
      2) Temporary queues
      create a queue with a random name



    result = channel.queue_declare()
      once we disconnect the consumer the queue should be deleted. There's an exclusiveflag for that:



    result = channel.queue_declare(exclusive=True)
      3) Bindings
      we need to tell the exchange to send messages to our queue. That relationship between exchange and a queue is called a binding.



    channel.queue_bind(exchange='logs',
    queue=result.method.queue)
      4) Sending



    # routing_key is ignored for fanout exchanges
    channel.basic_publish(exchange='logs',
    routing_key='',
    body=message)
      5) Receiving



    #!/usr/bin/env python
    import pika
    connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
    channel = connection.channel()
    channel.exchange_declare(exchange='logs',
    type='fanout')
    # temp queue
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    # bind q to exchange
    channel.queue_bind(exchange='logs',
    queue=queue_name)
    print('
  • Waiting for logs. To exit press CTRL+C')
    def callback(ch, method, properties, body):
    print(" [x] %r" % body)
    channel.basic_consume(callback,
    queue=queue_name,
    no_ack=True)
    channel.start_consuming()
    Routing
      Be able to subscribe only to a subset of the messages --> create a binding with a key



    channel.queue_bind(exchange=exchange_name,
    queue=queue_name,
    routing_key='black') # binding key
      The meaning of a binding key depends on the exchange type. The fanout exchanges, which we used previously, simply ignored its value.
      fanout - only capable of mindless broadcasting
      Direct exchange
      a message goes to the queues whose binding key exactly matches the routing key of the message
      1) sending



    # creating exchange
    channel.exchange_declare(exchange='direct_logs',
    type='direct')
    # sending using direct exchange
    channel.basic_publish(exchange='direct_logs',
    routing_key=severity,
    body=message)
      2) Subscribing



    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    # bind q with binding key
    for severity in severities:
    channel.queue_bind(exchange='direct_logs',
    queue=queue_name,
    routing_key=severity)
    Remote procedure call
      1) Client interface, expose a method named call which sends an RPC request



    fibonacci_rpc = FibonacciRpcClient()
    result = fibonacci_rpc.call(4)
    print("fib(4) is %r" % result)
      2) In order to receive a response the client needs to send a 'callback' queue address with the request



    # create a temp queue to receive response
    result = channel.queue_declare(exclusive=True)
    callback_queue = result.method.queue
    # use default exchange to send request along with callback_queue
    channel.basic_publish(exchange='',
    routing_key='rpc_queue',
    properties=pika.BasicProperties(
    reply_to = callback_queue,
    ),
    body=request)
      for each RPC request, client sends messages with two properties: reply_to & correlation_id
      reply-to: set the callback queue
      correlation_id: set to a unique value for every request

    MySQL
      一对多:
      user table:



    mysql> select * from user;
    +----+----------+--------+
    | id | name     | course |
    +----+----------+--------+
    |  2 | alice    |      1 |
    |  3 | bob      |      1 |
    |  4 | caroline |      2 |
    |  5 | david    |      5 |
    |  6 | emma     |   NULL |
    +----+----------+--------+
      course table:



    mysql> select * from course;
    +----+------------+
    | id | name       |
    +----+------------+
    |  1 | html5      |
    |  2 | css3       |
    |  3 | javascript |
    |  4 | php        |
    |  5 | mysql      |
    +----+------------+

      建立外键关系:



    ALTER TABLE `user`
    ADD CONSTRAINT `FK_course`
    FOREIGN KEY (`course`) REFERENCES `course` (`id`)
    ON UPDATE CASCADE;
    连表:
      1) INNER JOIN:



    mysql> SELECT user.name, course.name
    -> FROM `user`
    -> INNER JOIN `course` on user.course = course.id;
    +----------+-------+
    | name     | name  |
    +----------+-------+
    | alice    | html5 |
    | bob      | html5 |
    | caroline | css3  |
    | david    | mysql |
    +----------+-------+
      A INNER JOIN produces a set of records which match in both the user and course tables
      2) LEFT JOIN:



    mysql> SELECT user.name, course.name
    -> FROM `user`
    -> LEFT JOIN `course` on user.course = course.id;
    +----------+-------+
    | name     | name  |
    +----------+-------+
    | alice    | html5 |
    | bob      | html5 |
    | caroline | css3  |
    | david    | mysql |
    | emma     | NULL  |
    +----------+-------+
      A LEFT JOIN produces a set of records which matches every entry in the left table (user) regardless of any matching entry in the right table (course)
      3) RIGHT JOIN:



    mysql> SELECT user.name, course.name
    -> FROM `user`
    -> RIGHT JOIN `course` on user.course = course.id;
    +----------+------------+
    | name     | name       |
    +----------+------------+
    | alice    | html5      |
    | bob      | html5      |
    | caroline | css3       |
    | NULL     | javascript |
    | NULL     | php        |
    | david    | mysql      |
    +----------+------------+
      4) UNION (OUTER JOIN):



    mysql> SELECT user.name, course.name
    -> FROM `user`
    -> LEFT JOIN `course` on user.course = course.id
    ->
    -> UNION
    ->
    -> SELECT user.name, course.name
    -> FROM `user`
    -> RIGHT JOIN `course` on user.course = course.id;
    +----------+------------+
    | name     | name       |
    +----------+------------+
    | alice    | html5      |
    | bob      | html5      |
    | caroline | css3       |
    | david    | mysql      |
    | emma     | NULL       |
    | NULL     | javascript |
    | NULL     | php        |
    +----------+------------+
      the OUTER JOIN which returns all records in both tables regardless of any match. Where no match exists, the missing side will contain NULL

  • 运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-390316-1-1.html 上篇帖子: RabbitMQ 实现RPC 下篇帖子: python rabittmq 使用
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表