Exemple #1
0
import pika
import time

auth = pika.PlainCredentials(
    username='******',
    password='******',
)  # 用户名 / 密码
connection = pika.BlockingConnection(
    pika.ConnectionParameters(
        '127.0.0.1',  # RabbitMQ 地址
        5672,  # 端口号
        '/',  # 虚拟主机
        auth,  # 验证
    ))  # 链接RabbitMQ
channel = connection.channel()  # 创建RabbitMQ通道

channel.queue_declare(
    queue='queue_name_test',  # 消费对列名
    durable=True,  # 持久化
)


def callback(ch, method, properties, body):
    print("消费者:  %r" % body)


channel.basic_consume(
    queue='queue_name_test',  # 对列名
    auto_ack=True,  # 自动回应
    on_message_callback=callback,  # 回调消息
)
Exemple #2
0
for arg in sys.argv:
    if arg == 'simple':
        speedTestSimple = True
    if arg == 'mini':
        speedTestMiniEnabled = True

#Initialise syslogger
syslog = logging.getLogger('Syslog')
syslog.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address='/dev/log')
syslog.addHandler(handler)

#Initialise rabbitmq connection
credentials = pika.PlainCredentials(username, password)
connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost', 5672, '/', credentials))
channel = connection.channel()
channel.queue_declare(queue=sendQueue)


#Log to syslog
def syslogger(message, severity):
    logtime = str(datetime.now())
    try:
        if severity == "info":
            syslog.info(logtime + ': ' + message)
        elif severity == "critical":
            syslog.critical(logtime + ': ' + message)
        elif severity == "debug":
            syslog.debug(logtime + ': ' + message)
        return True
Exemple #3
0
import pika
import json

with open('./test_optimization_simplex.json') as f:
    data = json.load(f)

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='sheep.rmq.cloudamqp.com',
                              port=5672,
                              credentials=pika.PlainCredentials(
                                  'ylfqreqi',
                                  'oe3Hqc_nPWomlp2eDnq5Chwtnfy3jnBk'),
                              virtual_host='ylfqreqi'))

channel = connection.channel()

channel.queue_declare(queue='optimization_request_queue', durable=True)

channel.basic_publish(exchange='',
                      routing_key='optimization_request_queue',
                      body=json.dumps(data).encode())

print(" [x] Sent Test Data")
connection.close()
Exemple #4
0
# coding: utf-8

# In[2]:

import pika
import datetime

# In[3]:

credentials = pika.PlainCredentials(username='******', password='******')
#connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.1.40',credentials=credentials))
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost', credentials=credentials))
channel = connection.channel()

# In[4]:

channel.queue_declare(queue='hello')

# In[ ]:

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')

print(" [x] Sent 'Hello World!'" + str(datetime.datetime.now()))
Exemple #5
0
import pika
'''https://www.cnblogs.com/shenh/p/10497244.html'''
from src.SocketTest.LoggingDemo import LoggingFactory
import requests

logfactory = LoggingFactory('info', 'debug')
log = logfactory.getLogger()
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='127.0.0.1',
                              port=5672,
                              virtual_host='/',
                              credentials=credentials))
log.info('连接队列...')
channel = connection.channel()
# 创建临时队列,队列名传空字符,consumer关闭后,队列自动删除
# exclusive=False,durable=True
result = channel.queue_declare('QUEUE_C', exclusive=False, durable=True)
# 声明exchange,由exchange指定消息在哪个队列传递,如不存在,则创建。durable = True 代表exchange持久化存储,False 非持久化存储
channel.exchange_declare(exchange='my-mq-exchange_C',
                         durable=True,
                         exchange_type='fanout')
# 绑定exchange和队列  exchange 使我们能够确切地指定消息应该到哪个队列去
channel.queue_bind(exchange='my-mq-exchange_C', queue=result.method.queue)
# 定义一个回调函数来处理消息队列中的消息,这里是打印出来
log.info('获取队列(QUEUE_C)信息...')


def callback(ch, method, properties, body):
    ch.basic_ack(delivery_tag=method.delivery_tag)
    url = str(body.decode())
Exemple #6
0
import pika
import sys

'''
	Отправляет одно сообщение в очередь
'''

# Подключаемся к брокеру на локальном хосте. Для подключения к брокеру на другой машине нужно указать её ip вместо localhost
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1'))
channel = connection.channel()

# создаёт точку обмена
channel.exchange_declare(
	exchange='topic_logs', 
	exchange_type='topic'
)

# Создаём очередь. Если послать сообщение в несуществующую очередь, то рэбит его проигнорирует (создаёт очередь с этим именем только один раз), urable=True делает очередь устойчивой 
# channel.queue_declare(queue='one', durable=True)

# Отправляем сообщение в очередь
channel.basic_publish(
	exchange='topic_logs',
	routing_key=sys.argv[1],
	body=sys.argv[1],
	properties=pika.BasicProperties(
		# позволяет сделать сообщения устойчивыми
		delivery_mode = 2,
	)
)
Exemple #7
0
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbit'))
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()
Exemple #8
0
from django.db.models import TextField
from .amqppublisher import AMQPPublisher
from django.db.models import Avg, Max, Min, Sum

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = environ.Env()
environ.Env.read_env(BASE_DIR + "/.env")  # reading .env file

PROCESSING_TIME_WINDOW = 300  # IN SECONDS (300 seconds => 5 minutes)
PROCESSING_INTERVAL = 10  # IN SECONDS

# DEFAULT_PARTICIPANT_TO_SERVER_ROUTING_KEY = "PARTICIPANT_TO_SERVER"

credentials = pika.PlainCredentials(env('RABBITUSER'), env('RABBITPASS'))
parameters = pika.ConnectionParameters(env('RABBITHOST'), env('RABBITPORT'),
                                       env('RABBITVHOST'), credentials)

# connection_recv = pika.BlockingConnection(parameters)
# channel_recv = connection_recv.channel()
# queue_name_recv = channel_recv.queue_declare('', exclusive=True).method.queue
# channel_recv.queue_bind(exchange="amq.topic", routing_key=DEFAULT_PARTICIPANT_TO_SERVER_ROUTING_KEY, queue=queue_name_recv)

# amqp_url = 'amqp://'+ env('RABBITUSER') +':'+ env('RABBITPASS') +'@'+ env('RABBITHOST') +':'+ env('RABBITPORT') +'/%2F?connection_attempts=30&heartbeat=3600'
# publisher = AMQPPublisher(amqp_url)
# publisher.run()
# publisher.publish_message("TES123")


class MAJORITY_Thread(threading.Thread):
    channel = None
#!/usr/bin/env python
import pika
import sys

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

channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs', routing_key='', body=message)
print(" [x] Sent %r" % message)
connection.close()
Exemple #10
0
def send_notification(bookingID):
    status = 201
    result = {}

    # check if booking exists
    if (not (Booking.query.filter_by(bookingID=bookingID).first())):
        status = 400
        result = {
            "status":
            status,
            "message":
            "A booking with bookingID '{}' does not exists. E-mail cannot be sent."
            .format(bookingID)
        }
    else:
        # check if booking has ended
        bookingData = Booking.query.filter_by(bookingID=bookingID).first()
        booking = json.dumps(bookingData, default=str)
        print(booking)
        dbEndTime = bookingData.endTime
        if (dbEndTime == None):
            status = 400
            result = {
                "status":
                status,
                "message":
                "A booking with bookingID '{}' has not ended.".format(
                    bookingID)
            }
        # check if email enterted is empty
        else:
            data = request.get_json()
            if (data['email'] == ""):
                status = 400
                result = {"status": status, "message": "Invalid email entered"}

            # send message to broker
            else:
                hostname = "rabbitmq"
                port = 5672

                connection = pika.BlockingConnection(
                    pika.ConnectionParameters(host=hostname, port=port))

                channel = connection.channel()
                exchangename = "notification_direct"
                channel.exchange_declare(exchange=exchangename,
                                         exchange_type='direct')

                emailData = dict()
                emailData['cost'] = data['cost']
                emailData['email'] = data['email']
                emailData['bookingID'] = bookingData.bookingID
                emailData['scooterID'] = bookingData.scooterID
                emailData['startTime'] = bookingData.startTime
                emailData['endTime'] = bookingData.endTime

                message = json.dumps(emailData, default=str)
                channel.queue_declare(queue='email', durable=True)
                channel.queue_bind(exchange=exchangename,
                                   queue='email',
                                   routing_key='notification.email')
                channel.basic_publish(
                    exchange=exchangename,
                    routing_key="notification.email",
                    body=message,
                    properties=pika.BasicProperties(delivery_mode=2))
                result = {
                    "status":
                    status,
                    "message":
                    "Your ride summary has been sent to your designated email.\nThank you!"
                }
                print("email request sent to notification...")
                connection.close()

    return result
Exemple #11
0
# -*- coding:utf-8 -*-
# __author__ = 'gupan'
import sys
import pika
user_pwd = pika.PlainCredentials("admin", '123456')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.17.136', credentials=user_pwd))

channel = connection.channel()
# 声明一个exchange,名称为logs,类型是fanout
channel.exchange_declare(exchange="logs", exchange_type="fanout")

msg = "".join(sys.argv[1:]) or "info: Hello World!"

channel.basic_publish(
    # exchange名称为logs
    exchange='logs',
    # routing_key参数保留,为空
    routing_key='',
    body=msg,
    properties=pika.BasicProperties(delivery_mode=2))

connection.close()
# -*- coding:utf-8 -*-
# py queue  典型应用 生产者消费者模型
# threading   queue 多个线程之间数据同步和交互
# multiprocessing  queue 父进程与子进程或者同一父进程下的多个子进程交互
import pika

username = "******"
pwd = "qq2921481"
user_pwd = pika.PlainCredentials(username, pwd)

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='172.16.54.130', credentials=user_pwd))
channel = connection.channel()

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

channel.basic_publish(
    exchange='',  # 这里不写exchange
    routing_key='hello',
    body='Hello World',
    properties=pika.BasicProperties(delivery_mode=2)  # 队列消息持久化
)

print("send hello world")

connection.close()
Exemple #13
0
import pika

credentials = pika.PlainCredentials('admin', 'admin')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host ='25.121.196.54', port=5672, virtual_host= "vh1", credentials=credentials))
channel = connection.channel()

channel.queue_declare(queue='hello')

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


import django
django.setup()
from items_service.models import Items
import datetime
import threading
import schedule
import time
import items_service.config as config
import requests
import json
import pika
import pickle

# Compare auction start time and end time to current time to set auction_live_now variable - which has implications for what users can see
print("CARTS TASK STARTING", flush=True)
connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.RABBIT_HOST))
channel = connection.channel()
print(' [*] Waiting for items to move to carts', flush=True)
channel.exchange_declare(exchange='cart_items', exchange_type='topic')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='cart_items', queue=queue_name, routing_key='cart_items')

def callback(ch, method, properties, body):
    body = pickle.loads(body)
    print(" [x] Received %r" % body, flush=True)
    item_id = body["item_id"]
    account_id = body["account_id"]
    price = body["price"]
Exemple #15
0
# -*- coding: utf-8 -*-
"""
@Author: 王剑威
@Time: 2021/2/21 9:16 上午
"""
import pika

# 连接凭证
credentials = pika.PlainCredentials("admin", "admin")
# 连接参数
parameters = pika.ConnectionParameters(host='127.0.0.1',
                                       port=5672,
                                       credentials=credentials)
# 建立连接
connection = pika.BlockingConnection(parameters)
# 创建channel
channel = connection.channel()
# 创建队列
queue = "work_queues"
# 已经存在的队列不会重复创建(但要保证队列的参数一直)
channel.queue_declare(queue=queue)
"""
参数:
    queue: 队列名称
    passive=False,
    durable=False: 是否持久化
    exclusive=False: 只允许当前的链接访问
    auto_delete=False: 断开链接后是否自动删除
    arguments=None: 队列的自定义键/值参数
"""
# 发布消息
Exemple #16
0
import pika
import json
from handlers import catalog_handler, product_handler

credentials = pika.PlainCredentials('user', 'user')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('rabbit', 5672, '/', credentials))

channel = connection.channel()

channel.queue_declare(queue='app_que', durable=True)
channel.exchange_declare(exchange='app_que_ex', exchange_type='fanout')

channel.queue_bind(exchange='app_que_ex', queue='app_que')


def callback(ch, method, properties, body):
    json_body = json.loads(body.decode())
    type_number = json_body['type']
    data = json_body['data']
    if type_number == 1:
        catalog_handler.add_new_category(data)
    elif type_number == 2:
        product_handler.add_new_product(data)
    elif type_number == 3:
        catalog_handler.update_category(data)
    elif type_number == 4:
        product_handler.update_product(data)
    elif type_number == 5:
        catalog_handler.delete_category(int(data["id"]))
    elif type_number == 6:
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika
import sys


credentials = pika.PlainCredentials('alex', '123')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.112.128',credentials=credentials))


channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         exchange_type='direct')


result = channel.queue_declare(queue="",exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                       routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')
Exemple #18
0
import time

import pika

username = '******'
pwd = 'dio'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(
    pika.ConnectionParameters('192.168.1.129', credentials=user_pwd))
chan = s_conn.channel()

chan.queue_declare(queue='sporttery_tickets', durable=True)


def callback(ch, method, properties, body):
    print("[消费者1] recv %s, %s" % (body, properties))
    time.sleep(1)
    ch.basic_ack(delivery_tag=method.delivery_tag)


chan.basic_qos(prefetch_count=1)
chan.basic_consume(callback, queue='sporttery_tickets')
chan.start_consuming()
Exemple #19
0
#!/usr/bin/env python
import pika

msgbody = 'Hello3 World!'

lbIP = '134.221.121.65'
#lbIP='localhost'

lbPort = 5670

credentials = pika.PlainCredentials('user1', 'password1')
parameters = pika.ConnectionParameters(host=lbIP,
                                       port=lbPort,
                                       virtual_host='vhost1',
                                       credentials=credentials)

for i in range(1, 5):
    connection = pika.BlockingConnection(parameters)

    channel = connection.channel()
    channel.queue_declare(queue='hello200' + str(i))
    connection.close()

#master (home node) w.r.t. queue is the node on which queue was first time declared (Q master), NOT the master of the cluster
#If we have a Round robin LB and close connection in a loop queues are declared in a round robin fashion on the cluster nodes
#if we keep only queue_declare in a loop, all queues will end up on the same node

#https://www.erlang-solutions.com/blog/take-control-of-your-rabbitmq-queues.html
#Currently, there are three queue master location strategies available;
#Min-Masters: Selects the master node as the one with the least running master queues. Configured as min-masters.
#Client-local: Like previous default node selection policy, this strategy selects the queue master node as the local node on which the queue is being declared. Configured as client-local.
Exemple #20
0
import pika
import random
import json
import time

import os

connection = pika.BlockingConnection(pika.ConnectionParameters('deti-engsoft-09.ua.pt'))
channel = connection.channel

QUEUE_NAME = "cities"

class Generator:

    def __init__(self, file):
        __location__ = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
        file = os.path.join(__location__, file)
        f = open(file, "r")
        self.cities = json.loads(f.read())["cities"]
        f.close()
        for i in range(len(self.cities)):
            self.cities[i]["id"] = i + 1

    def __generate(self):
        for city in self.cities:
            city["co"] = float(random.randint(0, 1200))  # bppv
            city["co2"] = float(random.randint(38, 420))  # ppm
            city["so2"] = float(random.randint(5, 35))  # micrg/m^3
            city["no2"] = float(random.randint(0, 80)) #mol/m^2
            city["o3"] = float(random.randint(11, 86)) # ppbv
Exemple #21
0
# )
# def fuck_it(){
#
# }
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)) + "\\..\\..\\")
import pika
import json
import re
from loach.utils.redisobj import douyin_rds
from json.decoder import JSONDecodeError

con = pika.BlockingConnection(
    pika.ConnectionParameters(host='xxx',
                              port=5672,
                              virtual_host='/',
                              credentials=pika.PlainCredentials('xxx', 'xxx')))
channel = con.channel()

binding_keys = [
    # routing_key       queue_name
    'kuaishou.author.kol',
    'kuaishou.author.kol'
]
# "\"share_info\": ?\"userId= ?(?<kid>[A-Za-z0-9]+)&photoId= ?(?<vid>[A-Za-z0-9]+)\""
p1 = re.compile(
    r'"share_info\": ?\"userId= ?(?P<kid>[A-Za-z0-9]+)&photoId= ?(?P<vid>[A-Za-z0-9]+)\"'
)
p2 = re.compile(r'\"user_id\": ?(?P<uid>\d+)')

Exemple #22
0
import pika
import sys

host = "127.0.0.1"
user = "******"
password = "******"
credentials = pika.PlainCredentials(username=user, password=password)
para = pika.ConnectionParameters(host=host,
                                 virtual_host="/leap",
                                 credentials=credentials)
con = pika.BlockingConnection(parameters=para)
channelmq = con.channel()
channelmq.exchange_declare(exchange="topic_log", type="topic")

# routing_keys=sys.argv[1] if len(sys.argv) >2 else "anonymous.info"
# message=' '.join(sys.argv[2:])  or "hellor world"
# channelmq.basic_publish(exchange="topic_log",routing_key=routing_keys,body=message)
# print "[x]  send %r:%r"  %(routing_keys,message)
# con.close()
result = channelmq.queue_declare(exclusive=True)
queue_name = result.method.queue

binding_keys = sys.argv[1:]
if not binding_keys:
    sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    sys.exit(1)

for binding_key in binding_keys:
    channelmq.queue_bind(exchange='topic_log',
                         queue=queue_name,
                         routing_key=binding_key)
Exemple #23
0
import pika

credentials = pika.PlainCredentials('zx2005', 'redhat')

# 使用上面定义的用户名密码,连接远程的队列服务器
connection = pika.BlockingConnection(
    pika.ConnectionParameters("10.1.1.128", credentials=credentials))

# 在tcp连接基础上,建立rabbit协议连接
channel = connection.channel()

# 申明一个广播类型的交换器
channel.exchange_declare(exchange='logs', exchange_type='fanout')

# 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue  # 取得随机队列的名字

# 使得队列接收交换器发来的消息
channel.queue_bind(exchange='logs', queue=queue_name)


# 从自己申明的队列接收广播消息
def callback(ch, method, properties, body):
    print(" [x] %r" % body)


# 开始从队列中取出数据
channel.basic_consume(callback, queue=queue_name, no_ack=True)
channel.start_consuming()
Exemple #24
0
 def run(self):
     connection = pika.BlockingConnection(pika.ConnectionParameters(HOST))
     channel = connection.channel()
     channel.queue_declare(queue=QUEUE)
     channel.basic_consume(callback, queue=QUEUE, no_ack=True)
     channel.start_consuming()
Exemple #25
0
import pika
import sys
import json

input_queue = sys.argv[1]
output_queue = sys.argv[2]
final_queue = sys.argv[3]

conn = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = conn.channel()

channel.queue_declare(queue=input_queue)
channel.queue_declare(queue=output_queue)
channel.queue_declare(queue=final_queue)

last_val = {}
min_val = 1000000.0


def update_min(ch, method, properties, body):
    global min_val, last_val
    connection = pika.BlockingConnection(
        pika.ConnectionParameters('localhost'))
    chan = connection.channel()
    body_json = json.loads(body)
    val = body_json['val']
    final_op = body_json['finalop']
    if val == 'FINAL':
        if final_op == 'min':
            chan.basic_publish(exchange='',
                               routing_key=final_queue,
#/usr/bin/env python
import pika

credentials = pika.PlainCredentials('uitsdbkq', 'oVMBBKTj_Axu6BqIArCWs79oNtxIJGvH')
connection = pika.BlockingConnection(pika.ConnectionParameters(
               'fox.rmq.cloudamqp.com', 5672, 'uitsdbkq', credentials))
channel = connection.channel()


channel.queue_declare(queue='hello')

print ' [*] Waiting for messages. To exit press CTRL+C'

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

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

channel.start_consuming()
Exemple #27
0
#!/usr/bin/env python3

import json
import sys

import pika

QUEUE_NAME = "profile"
RABBIT_HOST = "localhost"


def post_message(channel, message):
    channel.basic_publish(exchange="", routing_key=QUEUE_NAME, body=message)
    print(" [x] Sent '%s'" % message)


if __name__ == "__main__":
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(RABBIT_HOST))
    channel = connection.channel()
    channel.queue_declare(queue=QUEUE_NAME)

    login = sys.argv[1]
    password = sys.argv[2]

    post_message(channel, json.dumps({"login": login, "password": password}))
    connection.close()

    exit()
Exemple #28
0
def send_order(data):
    # hostname = "localhost" # default broker hostname. Web management interface default at http://localhost:15672
    # port = 5672 # default messaging port.
    # # connect to the broker and set up a communication channel in the connection
    # connection = pika.BlockingConnection(pika.ConnectionParameters(host=hostname, port=port))
    #     # Note: various network firewalls, filters, gateways (e.g., SMU VPN on wifi), may hinder the connections;
    #     # If "pika.exceptions.AMQPConnectionError" happens, may try again after disconnecting the wifi and/or disabling firewalls

    hostname = "host.docker.internal"  # default broker hostname. Web management interface default at http://localhost:15672
    port = 5672  # default messaging port.
    # connect to the broker and set up a communication channel in the
    credentials = pika.PlainCredentials('guest', 'guest')
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=hostname,
                                  port=port,
                                  virtual_host="/",
                                  credentials=credentials))
    channel = connection.channel()
    # set up the exchange if the exchange doesn't exist
    exchangename = "edutrade"
    channel.exchange_declare(exchange=exchangename, exchange_type='direct')

    # extract the data out for the message

    # prepare the message body content
    message = json.dumps(data,
                         default=str)  # convert a JSON object to a string

    # Prepare the correlation id and reply_to queue and do some record keeping
    corrid = str(uuid.uuid4())
    row = {"correlation_id": corrid, "status": ""}
    correlation = TransactionCorrelation(**row)
    # add correlation row into database
    try:
        db.session.add(correlation)
        db.session.commit()
    except:
        return jsonify({"message":
                        "An error occurred creating a request."}), 500
    replyqueuename = "trading.reply"
    # prepare the channel and send a message to Stock
    channel.queue_declare(
        queue='trading',
        durable=True)  # make sure the queue used by Shipping exist and durable
    channel.queue_bind(exchange=exchangename,
                       queue='trading',
                       routing_key='trading.info'
                       )  # make sure the queue is bound to the exchange
    channel.basic_publish(
        exchange=exchangename,
        routing_key="trading.info",
        body=message,
        properties=pika.BasicProperties(
            delivery_mode=
            2,  # make message persistent within the matching queues until it is received by some receiver (the matching queues have to exist and be durable and bound to the exchange, which are ensured by the previous two api calls)
            reply_to=
            replyqueuename,  # set the reply queue which will be used as the routing key for reply messages
            correlation_id=
            corrid  # set the correlation id for easier matching of replies
        ))
    print(f"{data['symbol']} request sent to user management microservice.")
    # close the connection to the broker
    connection.close()
    return corrid
#!/usr/bin/env python3
import pika
import sys

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

channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                       routing_key=severity)

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


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


channel.basic_consume(callback, queue=queue_name, no_ack=True)
Exemple #30
0
def get_rmq() -> pika.BlockingConnection:
    """Get a RabbitMQ connection object. Create one if it doesn't exist."""
    if 'rmq' not in __STORE:
        __STORE['r_mq'] = pika.BlockingConnection(
            pika.ConnectionParameters(RMQ_HOST))
    return __STORE['r_mq']