Ejemplo n.º 1
0
def create_que(params, channel):
    try:
        channel.queue_declare(queue=params.queue)
        rmq_tools.console_log("Очередь", params.queue, "успешно создана")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Очередь", params.queue, "уже есть в кролике!")
        rmq_tools.console_log(
            "Проверьте параметры и запустите программу повторно")
        exit()
Ejemplo n.º 2
0
def batch_sending(params):
    try:
        check_list = ["rmq", "e", "rk"]
        list_messages = yaml.load(params.message_file.read(),
                                  Loader=yaml.FullLoader)
        for params_message in list_messages:
            if rmq_tools.check_prarms(check_list, params_message['params']):
                if len(params_message['messages']) != 0:
                    rmq_tools.send_batch(params_message)
                else:
                    print(
                        f'message - {str(params_message["messages"])} - ключ message пустой'
                    )
                    return
            else:
                return
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка публикации сообщения!")
Ejemplo n.º 3
0
def delete(params, channel):
    try:
        channel.queue_delete(queue=params.queue)
        rmq_tools.console_log("Очередь", params.queue, "успешно удалена")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка удаления очереди!")
Ejemplo n.º 4
0
def purge(params, channel):
    try:
        channel.queue_purge(queue=params.queue)
        rmq_tools.console_log("Очередь", params.queue, "успешно очищена")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка очистки очереди", params.queue, "!")
Ejemplo n.º 5
0
def create_que(params, channel):
    try:
        channel.queue_declare(queue=params.queue, durable=params.durable)
        rmq_tools.console_log("Очередь", params.queue, "успешно создана")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка создания очереди!")
Ejemplo n.º 6
0
def create_exch(params, channel):
    try:
        channel.exchange_declare(exchange=params.exch, exchange_type=params.type, durable=params.durable)
        rmq_tools.console_log("Exchange", params.exch, "успешно создан")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка создания exchange!")
Ejemplo n.º 7
0
def bind(params, channel):
    try:
        channel.queue_bind(exchange=params.exch,
                           queue=params.queue,
                           routing_key=params.r_key)
        rmq_tools.console_log("Сообщения с routing_key = ", params.r_key,
                              "\nуспешно назначены для пересылки из ",
                              params.exch, "\nв очередь", params.queue)
    except Exception:
        delete(params, channel)
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка создания binding!")
        rmq_tools.console_log(
            "Проверьте параметры и запустите программу повторно")
        exit()
Ejemplo n.º 8
0
def unbind(params, channel):
    try:
        channel.queue_unbind(exchange=params.exch, queue=params.queue, routing_key=params.r_key)
        rmq_tools.console_log("Пересылка сообщений с routing_key = ",
                              params.r_key, "\n из ", params.exch, "\nв очередь", params.queue, "успешно прекращена")
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка удаления binding!")
Ejemplo n.º 9
0
def on_message(channel, method_frame, header_frame, body):
    """Обработчик для считанных из "кролика" сообщений. Записывает полученное сообщение в файл или выводит в консоль

    Args:
         channel:       объект соединения с RabbitMQ
         method_frame:  объект с служебными параметрами сообщения из кролика
         header_frame:  объект, содержащий заголовок сообщения
         body:          тело сообщения
    """
    global all_cnt, lim
    if all_cnt >= lim:
        rmq_tools.console_log('Достаточное количество информации собрано.')
        raise KeyboardInterrupt
    body_str = body.decode("utf-8")[:4000]
    rkey = method_frame.routing_key
    cmd_line_arguments.file.write(rkey + '\n')
    cmd_line_arguments.file.write(body_str + '\n\n')
    all_cnt = all_cnt + 1
    if (lim != 0) and (cmd_line_arguments.file == sys.stdout):
        sys.stdout.write(
            f'[{rmq_tools.time_now()}] - {all_cnt} of {lim} messages consumed.\r'
        )
    channel.basic_ack(delivery_tag=method_frame.delivery_tag)
Ejemplo n.º 10
0
def bind(params, channel):
    try:
        channel.queue_bind(exchange=params.exch, queue=params.queue, routing_key=params.r_key)
        rmq_tools.console_log("Сообщения с routing_key = ",
                              params.r_key, "\nуспешно назначены для пересылки из ", params.exch, "\nв очередь",
                              params.queue)
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка создания binding!")
Ejemplo n.º 11
0
def from_console(params, channel):
    try:
        channel.basic_publish(exchange=params.exch,
                              routing_key=params.r_key,
                              body=params.message)
        rmq_tools.console_log("Сообщение: \n", params.message,
                              "\nс routing_key =", params.r_key,
                              "\nуспешно опубликовано в exchange - ",
                              params.exch)
    except Exception:
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log("Ошибка публикации сообщения!")
Ejemplo n.º 12
0
def from_existing_que(params, channel):
    rmq_tools.console_log("Начитаем считывание.")
    channel.basic_consume(on_message, queue=params.queue)
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()
    except Exception:
        channel.stop_consuming()
        rmq_tools.console_log("Ошибка:\n", traceback.format_exc())
        rmq_tools.console_log(
            "Consumer аварийно завершил работу! Обратитесь к разработчику для устранения проблемы."
        )