#!/usr/bin/env python import pika import os import time import serial credentials = pika.PlainCredentials('asus', 'asus') connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.0.103', 5672, '/', credentials)) # Connect to CloudAMQP channel = connection.channel() channel.exchange_declare(exchange='command', type='fanout') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange='command', queue=queue_name) channel1 = connection.channel() channel1.exchange_declare(exchange='mensaje', type='fanout') msg = "Escuchando Comandos presionados" channel1.basic_publish(exchange='mensaje', routing_key='', body=msg) ser = serial.Serial("/dev/ttyS0", 57600) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) msg = str(body) channel1.basic_publish(exchange='mensaje', routing_key='', body=msg)
import pika, sys import time import json credentials = pika.PlainCredentials("wutao", "12345678") #conn_params = pika.ConnectionParameters(host= "localhost",port=5672, credentials=credentials) conn_params = pika.ConnectionParameters(host="192.168.7.19", port=5672, virtual_host="OutTrig", credentials=credentials) conn_broker = pika.BlockingConnection(conn_params) channel = conn_broker.channel() channel.exchange_declare(exchange="AiOut.tr", exchange_type="fanout", passive=False, durable=False, auto_delete=True) channel2 = conn_broker.channel() channel2.exchange_declare(exchange="ReOut.tr", exchange_type="fanout", passive=False, durable=False, auto_delete=True) #msg = sys.argv[1] msg = "hello" + str(time.localtime()) msg_props = pika.BasicProperties() msg_props.content_type = "text/plain"
#!/usr/bin/env python #coding=utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost'))#连接到rabbitmq服务器 channel = connection.channel() channel.queue_declare(queue='hello') #声明消息队列,消息将在这个队列中进行传递 x={'a':1, 'b':2, 'c':3} y=str(x) channel.basic_publish(exchange='', routing_key='hello', body=y) #发送消息到上面声明的hello队列,其中exchange表示交换器,能精确指定消息应该发送到哪个队列, #routing_key设置为队列的名称,body就是发送的内容,具体发送细节暂时先不关注 print y connection.close()
import pika import sys # Set the connection parameters to connect to rabbit-server1 on port 5672 # on the / virtual host using the username "guest" and password "guest" username = '******' password = '******' hostname = 'localhost' virtualhost = '/' credentials = pika.PlainCredentials(username, password) parameters = pika.ConnectionParameters(hostname, 5672, virtualhost, credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() exchange_name = 'patient_data' channel.exchange_declare(exchange=exchange_name, exchange_type='topic') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue binding_keys = "#" if not binding_keys: sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) sys.exit(1)
import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost', port=5672) ) channel = connection.channel() channel.queue_declare(queue='my-queue', durable=True) def callback(ch, method, properties, body): print('received') channel.basic_consume( queue='my-queue', on_message_callback=callback, auto_ack=True ) print('waiting for messages') channel.start_consuming()
# -*- coding: utf-8 -*- # @Time : 2021/2/8 16:19 # @Author : wanghao # @File : 生产者_发布者.py # @Software: PyCharm import pika # 有密码的连接方式 credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.56.101', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='m3', exchange_type='topic') channel.basic_publish( exchange='m3', routing_key='old.ff', # 给队列名称发消息 body='x1') connection.close()
@author : Alban CREPEL @brief : a simple example of a remote procedure call on the client side """ import pika, os, uuid import msgpack import msgpack_numpy as m import numpy as np #if Numpy is required. amqp_url='amqp://*****:*****@impala.rmq.cloudamqp.com/hflgmxzc' url = os.environ.get('CLOUDAMQP_URL',amqp_url) params = pika.URLParameters(url) params.socket_timeout = 5 #initiate the connexion connection = pika.BlockingConnection(params) channel = connection.channel() result = channel.queue_declare(exclusive=True) callback_queue = result.method.queue request_msg = "Hi, how fine ?" message = {"type":0, "value":"Hi, how fine?"} encoded_message = msgpack.packb(message, default = m.encode) print(request_msg) corr_id = str(uuid.uuid4()) channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties(
import pika import json import os import face_recognition credentail = pika.PlainCredentials('face-recognition', 'face123') connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.0.226', port=5672, virtual_host='/', credentials=credentail)) channel = connection.channel() channel.queue_declare(queue='testings', durable=True) # connection = pika.BlockingConnection( # pika.ConnectionParameters(host='localhost', port=5672)) # channel = connection.channel() # channel.queue_declare(queue='show_queue', durable=True) count = 0 for image in os.listdir("test_image"): X_img = face_recognition.load_image_file("test_image/" + image) X_face_locations = face_recognition.face_locations(X_img) faces_encode = face_recognition.face_encodings( X_img, known_face_locations=X_face_locations)[0] res = faces_encode.tolist() channel.basic_publish( exchange='', routing_key='testings', body=json.dumps(res), properties=pika.BasicProperties( delivery_mode=2, # make message persistent ))
import pika connection = pika.BlockingConnection() channel = connection.channel() for method_frame, properties, body in channel.consume('test'): # Display the message parts and acknowledge the message print(method_frame, properties, body) channel.basic_ack(method_frame.delivery_tag) if method_frame.delivery_tag == 10: break # Escape out of the loop after 10 messages # Cancel the consumer and return any pending messages requeued_messages = channel.cancel() print('Requeued %i messages' % requeued_messages) connection.close()
import pika import time credentials = pika.PlainCredentials("michael", "michael") connection = pika.BlockingConnection( pika.ConnectionParameters(host='192.168.2.188', credentials=credentials)) channel = connection.channel() channel.queue_declare( queue='task_queue', durable=True, ) print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body): if body == "task_queue": ch.basic_reject(requeue=False) else: print " [x] Received %r" % (body, ) ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='task_queue') channel.start_consuming()
import pika import random import time connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) #here i'am connecting to a brokaer channel = connection.channel() channel.queue_declare(queue='bufor',durable=True) #create queue names bufor while(True): message = str(random.randrange(0,5,1)) channel.basic_publish( exchange='', routing_key='bufor', body=message, properties=pika.BasicProperties( delivery_mode=2, )) # make message persistent, when program will crush, message will be still alive print("TEST",message) time.sleep(random.randrange(0,5,1)) connection.close()
def serverlist(self, mqAddress): self.asyncServerListConnection = pika.BlockingConnection(pika.ConnectionParameters( host=mqAddress)) self.asyncServerListlistener = threading.Thread(target=self.listenforserverlist, name= "asyncServerListlistenerThread", args=(self.asyncServerListConnection,)) self.asyncServerListlistener.start()
#!/usr/bin/env python import pika username = '******' # 指定远程rabbitmq的用户名密码 pwd = 'fanshan2020' user_pwd = pika.PlainCredentials(username, pwd) connection = pika.BlockingConnection(pika.ConnectionParameters(host='101.200.73.195', port=5010, credentials=user_pwd, virtual_host="my_rabbitmq")) channel = connection.channel() # channel.queue_declare(queue='hello', durable=True) channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close()
def get_channel(): connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) return connection.channel()
import pika import sys import pickle import time credentials = pika.PlainCredentials('oleg', '123456') connection = pika.BlockingConnection( pika.ConnectionParameters(host='node1', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='hello') class human: def __init__(self, age=10, name='Oleg'): self.age = age self.name = name for i in range(10): name = 'Oleksii ' + str(i) h1 = human(11, name) time.sleep(1) mess = pickle.dumps(h1, protocol=1) channel.basic_publish(exchange='', routing_key='hello', body=mess) print(" [x] Sent {0}".format(name)) connection.close()
import pika import logging import sys import time time.sleep(30) connection = pika.BlockingConnection( pika.ConnectionParameters(host='rabbitmq', port=5672)) channel = connection.channel() channel.queue_declare(queue='hello') line = '' while True: try: line = input(': ') except EOFError: break logging.debug("Sending '%s'" % line) channel.basic_publish(exchange='', routing_key='hello', body=line) logging.info("Sent '%s'" % line) print("Sent message '{}'".format(line)) connection.close()
def get_rabbit_connection(): if rabbitmq_url: connection = pika.BlockingConnection(pika.URLParameters(rabbitmq_url)) else: connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq')) return connection
import pika import utils import sys toSend = utils.readFile(sys.argv[1]) counter = 0 utils.startServerTestSetup("AMQPPublisher", sys.argv[1], int(sys.argv[2])) connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.2.2')) channel = connection.channel() channel.queue_declare(queue=" ".join(["AMQP", sys.argv[1], sys.argv[2]])) while counter < int(sys.argv[2]): try: channel.basic_publish(exchange='', routing_key=" ".join( ["AMQP", sys.argv[1], sys.argv[2]]), body=toSend) counter += 1 except: pass connection.close()
# -*- coding: utf-8 -*- """ Created on Mon Sep 30 16:02:59 2019 @author: salerogs """ import os import pika amqp_url = 'amqp://*****:*****@dove.rmq.cloudamqp.com/ssplddri' url = os.environ.get('CLOUDAMQP_URL', amqp_url) params = pika.URLParameters(url) params.socket_timeout = 5 #initiate the connexion connection = pika.BlockingConnection(params) # Connect to CloudAMQP channel = connection.channel() channel.queue_declare(queue='presentation') def callback(ch, method, properties, body): print("[X] Received %r" % body) channel.basic_consume(queue='presentation', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
import pika,time,sys credentials = pika.PlainCredentials('zx2005', 'redhat') # 使用上面定义的用户名密码,连接远程的队列服务器 connection = pika.BlockingConnection(pika.ConnectionParameters( "10.1.11.128", credentials=credentials )) # 在tcp连接基础上,建立rabbit协议连接 channel = connection.channel() # 发送端只需要申明交换器 channel.exchange_declare(exchange='logs',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()
import pika import json credentials = pika.PlainCredentials('one_user', 'qwertyui') # login + pass connection = pika.BlockingConnection( pika.ConnectionParameters( host='10.142.0.2', # host, in Google Cloud Internal IP port=5672, # port, usually 5672 or 15672 credentials=credentials # login + pass ) ) channel = connection.channel() def callback(ch, method, properties, body): if properties.content_type == 'application/json': d = json.loads(body.decode()) print(" [x] Received %r" % d) else: print(" [x] Received %r" % body.decode()) channel.queue_declare(queue='hello') # if not exists channel.basic_consume(queue='hello', auto_ack=True, on_message_callback=callback) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
import time import pika RABBITMQ_HOST = os.environ.get("RABBITMQ_HOST") RABBITMQ_USER = os.environ.get("RABBITMQ_USER") RABBITMQ_PASSWORD = os.environ.get("RABBITMQ_PASSWORD") RABBITMQ_QUEUE = os.environ.get("RABBITMQ_QUEUE") RABBITMQ_DURABLE = bool(os.environ.get("RABBITME_DURABLE")) RABBITMQ_PREFETCH_COUNT = int(os.environ.get("RABBITMQ_PREFETCH_COUNT")) credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD) connection = pika.BlockingConnection( pika.ConnectionParameters(host=RABBITMQ_HOST, credentials=credentials)) channel = connection.channel() channel.queue_declare(queue=RABBITMQ_QUEUE, durable=RABBITMQ_DURABLE) def callback(ch, method, properties, body): print("Received %r" % body) time.sleep(body.count(b'.')) print("Done") ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=RABBITMQ_PREFETCH_COUNT)
def event_publisher(self): full_event, event, data = (None, None, None) reconnect_attempts = 0 while not self._stopping: try: self._log.info( "Connecting to host: %s:%s virtual host: %s exchange: %s with user: %s ssl: %s" % ( self._params.host, self._params.port, self._params.virtual_host, self._exch, self._params.credentials.username, not self._params.ssl_options is None, )) self._conn = amqp.BlockingConnection(self._params) self._channel = self._conn.channel() self._channel.exchange_declare(self._exch, **self.EXCH_OPTS) reconnect_attempts = 0 while not self._stopping: try: # if variables are initialized we haven't sent them yet. # don't retrieve a new event, send the old one if (full_event is None) and (event is None) and (data is None): full_event, event, data = self._msg_queue.get( timeout=5) self._log.trace("send.start event=%s", full_event) self._channel.basic_publish(body=data, exchange=self._exch, routing_key=full_event) self._log.trace("send.end event=%s", event) # reset vars full_event, event, data = (None, None, None) # mark item as processed self._msg_queue.task_done() except queue.Empty: self._conn.process_data_events( ) # keep up with the AMQP heartbeats continue # Do not recover if connection was closed by broker except amqp.exceptions.ConnectionClosedByBroker as err: self._log.error( "Connection to %s:%s was closed by Broker - Not Recovering" % (self._params.host, self._params.port)) self._log.error( "Broker closed connection with: %s, stopping..." % err) self._conn = None break # Do not recover on channel errors except amqp.exceptions.AMQPChannelError as err: self._log.error("Channel error at %s:%s - Not Recovering" % (self._params.host, self._params.port)) self._log.error("Channel error: %s, stopping..." % err) self._conn = None break # Recover on all other connection errors if reconnect attempts is less than 5 except amqp.exceptions.AMQPConnectionError: reconnect_attempts += 1 if reconnect_attempts > 5: self._log.info( "Connection to %s:%s was closed - Not Recovering" % (self._params.host, self._params.port)) break else: self._log.info( "Connection to %s:%s was closed - Will try to recover the connection" % (self._params.host, self._params.port)) time.sleep(5) continue if not self._conn is None: self._log.trace("connection - close.start") self._conn.close() self._log.trace("connection - close.end")
""" @Datetime : 4/16/20 2:33 PM @Author : Fangyang """ import time import pika def callback(ch, method, props, body): print(f"[*] Received {body}") time.sleep(body.count(b'.')) print(f"[*] Done") ch.basic_ack(delivery_tag=method.delivery_tag) connection = pika.BlockingConnection(pika.ConnectionParameters("localhost")) channel = connection.channel() channel.queue_declare(queue="task_queue", durable=True) channel.basic_qos(prefetch_count=1) # 保证相同的任务这个worker身上只有一个任务, 不额外分配任务 channel.basic_consume( queue="task_queue", on_message_callback=callback, # auto_ack=True, # 默认为false, client处理消息时消息不丢失, client die了,由下一个client继续 ) print(f"[*] Waiting for messages. To exit press CTRL+C") channel.start_consuming() if __name__ == "__main__":
import twint import json import time import pika import os import logging from pebble import ProcessPool from datetime import datetime, timedelta from config import RABBITMQ_TWEETS logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __HOST__ = RABBITMQ_TWEETS connection = pika.BlockingConnection(pika.URLParameters(__HOST__)) channel = connection.channel() channel.queue_declare(queue='tweets', durable=True) def getTweets(query, _id): try: print(f'{_id}: {query}') # Configure c = twint.Config() c.Search = query c.Limit = 100 c.Pandas = True c.Hide_output = True twint.run.Search(c)
import socket import binascii def callback(ch, method, properties, body): print body ch.basic_ack(delivery_tag=method.delivery_tag) sys.exit() return info = ('maze', 'mazeAttack', 'maze', 31337) credentials = pika.PlainCredentials('guest', 'guest') parameters = pika.ConnectionParameters('172.17.0.2') connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='attackQueue', durable=True) userinfo = binascii.hexlify(os.urandom(32)).decode('ascii') #Stupid hack I found to get host ip s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) hostname = s.getsockname()[0] print(hostname) s.close() # A lot of this I won't need anymore service = { 'serviceName': 'dontneed',
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='topic_logs', exchange_type='topic') routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info' message = ' '.join(sys.argv[2:]) or 'Hello World!' channel.basic_publish(exchange='topic_logs', routing_key=routing_key, body=message) print(" [x] Sent %r:%r" % (routing_key, message)) connection.close()
return False if __name__ == "__main__": # Authenticate Twitter API user auth = tweepy.OAuthHandler(cr.CONSUMER_KEY, cr.CONSUMER_SECRET) auth.set_access_token(cr.ACCESS_TOKEN, cr.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) # wait for connection to RabbitMQ server to be established while True: try: # establish connection and queue on RabbitMQ connection = pika.BlockingConnection( pika.ConnectionParameters(host='rabbit', heartbeat=600)) channel = connection.channel() channel.queue_declare(queue='tweets_queue') # call stream listener myStreamListener = MyStreamListener() # request for Twitter API myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) # filter tweets by keywords and languages myStream.filter(languages=["en"], track=['Joe Biden', 'Biden'], is_async=False) except:
# Time: 2019/9/9 10:32 # Author jzh # File custom1.py import time import pika connection_host = '127.0.0.1' connection_credentials = pika.PlainCredentials('guest', 'guest') connection = pika.BlockingConnection( pika.ConnectionParameters(host=connection_host, credentials=connection_credentials)) channel = connection.channel() channel.queue_declare(queue='my_queue') def callback(ch, method, properties, body): print('消费者接收到消息: %s\n开始处理...' % body.decode()) time.sleep(len(body)) print('消息处理完成!') ch.basic_ack(delivery_tag=method.delivery_tag) # 设置公平调度 channel.basic_qos(prefetch_count=1) channel.basic_consume(queue='my_queue',
def lambda_handler(event, context): # Getting info of event (amazon lex) amount = event['currentIntent']['slots']['number'] product = event['currentIntent']['slots']['producto'] salon = event['currentIntent']['slots']['salon'] bebida = event['currentIntent']['slots']['bebida'] tarjeta = event['currentIntent']['slots']['tarjeta'] # Error Handling if salon not in salones_disponibles: return { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Lamentablemente el salon que escogio no se es correcto de la Universidad." } } } if len(tarjeta) < 5: return { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Lamentablemente no se logro procesar la orden. Favor verificar el numero de tarjeta" } } } # Hard coded for testing purposes fin_de_tarjeta = tarjeta[-4:] id_user = 1 x = { "id": "1", "name": product, "price": "5.75", "quantity": amount, "salon": salon, "bebida": bebida } json_to_send = json.dumps(x) # Database postgreSQL_select_Query = 'INSERT INTO public."Pedido"(id_pedido, pedido, fin_de_tarjeta, fecha, id_user) VALUES(DEFAULT,%s, %s, NOW(), 1)' cursor.execute(postgreSQL_select_Query, (json_to_send, fin_de_tarjeta)) connection.commit() count = cursor.rowcount print(count, "Record inserted successfully into product table") # RABBIT # parameters and credentials ready to support calls to RabbitMQ connection = pika.BlockingConnection( parameters) #Establishes TCP Connection with RabbitMQ channel = connection.channel( ) #Establishes logical channel within Connection channel.basic_publish( exchange='', routing_key='queue-pedidos', body='Howdy RabbitMQ, Lambda Here!! ' + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") + ' UTC') #Send Message connection.close() #Close Connection and Channel(s) within return { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Gracias por su orden de " + amount + " " + product + " al salon " + salon } } }