不死孤狼
IT 从来都是一个有新技术驱动的行业

send.py

#!usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/27 0:02
# @Author  : 黑咖啡
# @Email   : webaa88@126.com
# @File    : rabbitmq_send.py
# @Software: PyCharm

import pika
import time
import threading
import random

def sendmq(msg):
    print(msg)

    connection = pika.BlockingConnection(pika.ConnectionParameters(
                   '192.168.1.125'))      #localhost改成:192.168.1.118
    channel = connection.channel()    #建立了rabbit协议的通道

    #声明queue
    channel.queue_declare(queue='hello')

    #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    channel.basic_publish(exchange='',
                          routing_key='hello',
                          body='%s'%msg)
    #print(" [x] Sent 'Hello World!'")
    print(" [x] Sent:%s"%msg)
    connection.close()

if __name__ == '__main__':

    messages = ['q','z','z','c']
    # msg = random.randint(1,10)
    # print(msg)
    # a=threading.Thread(target=sendmq,args=(msg))
    for m in messages:
        print(m)
        a=threading.Thread(target=sendmq,args=(m))
        a.start()

  client.py

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.1.125'))
channel = connection.channel()

# 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.
#通道的实例    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()    #开始消息,是个死循环,一直监听收消息

  

posted on 2018-04-27 01:11  不死孤狼  阅读(105)  评论(0)    收藏  举报