def start(self): connection = pika.BlockingConnection(pika.ConnectionParameters('10.168.0.2', 5672, "/", pika.PlainCredentials('rabbit', '1'))) self.channel = connection.channel() self.channel.queue_declare(queue=MAIL_QUEUE, durable=True) self.channel.queue_declare(queue=REQUEST_QUEUE, durable=True) #self.channel.queue_declare(queue=RESPONSE_QUEUE, durable=True) self.channel.queue_declare(queue=REGISTER_QUEUE, durable=True)
import pika import time """ client = mqtt.Client('devbox', clean_session=True) client.username_pw_set('home', 'A@2cb13') client.connect('192.168.43.200') time.sleep(4) client.publish("home/lab/benchlight", "toggle",pip ) """ unpw = pika.PlainCredentials('home', 'A@2cb13') connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.43.200', virtual_host='home', credentials=unpw)) channel = connection.channel() channel.queue_declare(queue='lab/benchlight', durable=True) channel.basic_publish(exchange='', body='toggle', routing_key='lab/benchlight') print("message sent")
#!/usr/bin/env python3 import pika import time import json if __name__ == '__main__': ''' 发布算法调用指令至rabbitMQ服务器 ''' # 建立连接 credentials = pika.PlainCredentials('rossi', 'rossi1219') Parameter = pika.ConnectionParameters('10.39.251.182', 5672, '/', credentials) connection = pika.BlockingConnection(Parameter) channel = connection.channel() # 声明/指定消息队列 exchange_name = 'rossi_exchange_topic' channel.exchange_declare(exchange=exchange_name, exchange_type='topic') topic_key = "qdh_mytest" # 生成算法调用指令消息内容 dict = {} dict.update({'time': str(time.time())}) dict.update({'topic': topic_key}) dict.update({'taskid': "sdsgfdsdf23345"}) dict.update({ 'url': "http://img.mp.itc.cn/upload/20161210/7d24dd1648a94e6f9826f150d3f17f38_th.jpeg" }) dict.update({'operate': "face_analysis"})
import pika import pymysql import json import re import datetime conn = pymysql.connect("localhost", "root", "123456", "ossean") # 使用 cursor() 方法创建一个游标对象 cursor cursor = conn.cursor() conn.autocommit(1) now = datetime.datetime.now() credentials = pika.PlainCredentials('ossean', 'pdl123456') connection = pika.BlockingConnection( pika.ConnectionParameters('127.0.0.1', 5672, '/', credentials)) channel = connection.channel() channel.exchange_declare(exchange='broad', exchange_type='fanout') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange='broad', queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') pattern = r', \\"' num = 0 insert_repos = "insert ignore into relative_memo_to_open_source_projects_1(id,osp_id,relative_memo_id,match_weight,replies_num,view_num_crawled,memo_type,view_num_trustie,has_synchronized,created_time,match_time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" select_osp = "select id,name,source from open_source_projects_copy1 " update_memos = "update relative_memos_copy1 set history =1 where id =%s" cursor.execute(select_osp) osp_tuples = cursor.fetchall()
import pika import sys username = "******" pwd = 'shiwei666666' user_pwd = pika.PlainCredentials(username, pwd) # 创建连接 conn = pika.BlockingConnection(pika.ConnectionParameters("localhost", credentials=user_pwd)) #在连接上创建一个频道 channel = conn.channel() #创建一个交换机并声明 direct 的类型为:关键字类型,表示该交换机会根据消息中不同的关键字将消息发送给不同的队列 channel.exchange_declare(exchange="direct_logs", exchange_type="direct") severity = sys.argv[1] if len(sys.argv) > 1 else "info" message = ' '.join(sys.argv[2:]) or "Hello World!" channel.basic_publish(exchange='direct_logs', # 指明用于发布消息的交换机、关键字 routing_key=severity, # 绑定关键字,即将message与关键字info绑定,明确将消息发送到哪个关键字的队列中。 body=message) print(" [x] Sent %r" % message) conn.close()
import json, pika, io, random,curses, time, sys from curses import wrapper credentials = pika.PlainCredentials('123', '123') try: connection = pika.BlockingConnection(pika.ConnectionParameters('host', 5672, '/', credentials)) channel = connection.channel() except pika.exceptions.ConnectionClosed: print('** Unable to publish connection failed **') def straightMethod(stdscr): print('*** Press p to pause and c to continue ***') stdscr.nodelay(True) stdscr.clear() filepath = 'file.json' with open(filepath) as fp: for cnt, line in enumerate(fp): try: c = stdscr.getch() curses.flushinp() stdscr.clear() if c == ord('p'): while 1: stdscr.clear() c = stdscr.getch() if c == ord('c'): break else: pass print('*** sending msg ***')
import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='10.176.139.8', port=5672, virtual_host="/devops", credentials=pika.PlainCredentials( "devops", "q9wCFiEti7UuxYFPr3q0Xw"))) channel = connection.channel() def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume('world', callback, True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
# Version: 1.2 # Date: 13/07/2018 # # Description: Sends the details of the logon id to the RabbitMQ server (PiRMQ01) # #################################################################################### #!/usr/bin/python import pika import time import datetime import sys import os import socket # Use plain credentials for authentication mq_creds = pika.PlainCredentials(username="******", password="******") # Use localhost mq_params = pika.ConnectionParameters( host="192.168.1.200", # host = "sjholt.webhop.me", credentials=mq_creds, virtual_host="/") mq_exchange = "amq.topic" mq_routing_key = "PiCloud" mq_routing_key2 = "BlueMix" # This a connection object mq_conn = pika.BlockingConnection(mq_params)
def __init__(self, logger): self.logger = logger self.connection_parameters = pika.ConnectionParameters(host=RABBIT_ADDRESS, virtual_host='system', credentials=pika.PlainCredentials('service', RABBIT_PASSWORD), heartbeat_interval=300) self.queue = QUEUE
#!/usr/bin/env python import pika import sys #Las credenciales para conectarnos al servidor RabbitMQ credentials = pika.PlainCredentials('root', 'password') #Conexion con nuestro servidor RabbitMQ connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.0.10', credentials=credentials)) channel = connection.channel() #Declaramos el exchange channel.exchange_declare(exchange='topic-messages', exchange_type='topic') #Routing_key sera lo que nos permitira indicar hacia que grupo de consumidor ira el mensaje, y tambien se ingresara por consola routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info' #Mensaje que vamos a enviar el cual sera ingresado por consola, y por defecto enviara "Hola a todos" message = ' '.join(sys.argv[2:]) or 'Hola a todos' channel.basic_publish(exchange='topic-messages', routing_key=routing_key, body=message) print(" [x] Enviado %r:%r" % (routing_key, message)) #Cerramos la conexion connection.close()
queue_patrol_checkalive = 'system.autowarnner.patrol.checkalive' queue_commit = 'system.autowarnner.commit' login_url = 'http://' + itsm_ip + '/itsm/j_spring_security_check' warn_url_prfix = 'http://' + itsm_ip + '/itsm/itsmWarningInfoAction!pageSearch.action?_timestamp=' warn_detail_url = 'http://' + itsm_ip + '/itsm/itsmWarningInfoAction!view.action' warn_addlog_url = 'http://' + itsm_ip + '/itsm/itsmWarningInfoAction!addUserLog.action' warn_accept_url = 'http://' + itsm_ip + '/itsm/itsmWarningInfoAction!accept.action' warn_close_url = 'http://' + itsm_ip + '/itsm/itsmWarningInfoAction!close.action' #logger logging.config.fileConfig("logging.conf") logger = logging.getLogger("scanner") session = None authentication = pika.PlainCredentials('sysbot', 'sysbot') connection = pika.BlockingConnection( pika.ConnectionParameters(host=mq_server_ip, port=5672, credentials=authentication)) # json data postdata = { 'start': "0", 'end': "20", 'warTopic': '', # Topic search key word 'createDateBegin': "", 'createDateOver': "", 'queryWarOrigin': "40,160", # Warn srouce - sysm, nbu 'queryWarStatus': "" # Warn status - unhandled (10) }
#!/usr/bin/env python import pika # custome 消费者 server端 credentials = pika.PlainCredentials('rabbitmq', 'rabbitmq') connection = pika.BlockingConnection( pika.ConnectionParameters('localhost', 5672, '/', credentials)) channel = connection.channel() channel.queue_declare(queue='rpc_queue') def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) def on_request(ch, method, props, body): n = int(body) print(" [.] fib(%s)" % n) response = fib(n) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \
import pika credentials = pika.PlainCredentials('geektime', 'geektime') parameters = pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/', credentials=credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() # 消费者这里也要和订阅者一样声明 channel.exchange_declare(exchange='logs', exchange_type='fanout') # 声明消息队列 # exclusive当与消费者断开连接,队列被立即删除!!!!!!!!!!!!!!!!!!!!!。 result = channel.queue_declare( queue='', # 随即产生队列 exclusive=True) queue_name = result.method.queue # 与之前的差别是,这里需要通过交换机处理数据。 channel.queue_bind(exchange='logs', queue=queue_name) # 定义一个回调函数来处理消息队列中的消息 def callback(ch, method, properties, body): print(body.decode()) # 本例中使用自动确定
#!/usr/bin/python import pika, sys from pika import spec credentials = pika.PlainCredentials("guest", "guest") conn_params = pika.ConnectionParameters("localhost", credentials=credentials) conn_broker = pika.BlockingConnection(conn_params) channel = conn_broker.channel() def confirm_handler(frame): #/(hwppc.1) Publisher confirm handler if type(frame.method) == spec.Confirm.SelectOk: print "Channel in 'confirm' mode." elif type(frame.method) == spec.Basic.Nack: if frame.method.delivery_tag in msg_ids: print "Message lost!" elif type(frame.method) == spec.Basic.Ack: if frame.method.delivery_tag in msg_ids: print "Confirm received!" msg_ids.remove(frame.method.delivery_tag) #/(hwppc.2) Put channel in "confirm" mode channel.confirm_delivery(callback=confirm_handler) msg = sys.argv[1] msg_props = pika.BasicProperties() msg_props.content_type = "text/plain" msg_ids = [] #/(hwppc.3) Reset message ID tracker
# Taken from Jamieson Becker def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't have to be reachable s.connect(('10.255.255.255', 1)) IP = s.getsockname()[0] except: IP = '127.0.0.1' finally: s.close() return IP # create a connection and a channel credentials = pika.PlainCredentials('bob', 'dobbs') parameters = pika.ConnectionParameters(get_ip(), 5672, '/', credentials) connection = pika.BlockingConnection(parameters=parameters) channel = connection.channel() # if the queue already exists this call will do nothing channel.queue_declare(queue='task_queue', durable=True) print(' [*] Waiting for message. To exit press CTRL+C') # create a callback function received messages in the queue def callback(ch, method, properties, body): print(" [x] Received {!s}".format(body.decode('utf8'))) print("sleeping for {}".format(body.count(b'.'))) time.sleep(body.count(b'.')) print(" [x] Done")
#!/usr/bin/env python import pika import sys credentials = pika.PlainCredentials('nobleprog', 'nobleprog') connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost', 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') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body))
# import\ required file ------------------- from influxdb import InfluxDBClient import pika import sys import json import time # declarations-------------------- client = InfluxDBClient(host='localhost', port=8086) #def send_data_to_server(data): cred=pika.PlainCredentials('admin', 'password') connection = pika.BlockingConnection(pika.ConnectionParameters(host='34.224.98.65',credentials=cred)) print("connection-",connection) channel = connection.channel() channel.queue_declare(queue='local_queue', durable=True) # code---------------------- while True: time.sleep(10) data = read_from_db() send_data_to_server(data) def read_from_db(): print("----------------------\nin read from db") #client.switch_database('ftest') client.query("alter retention policy onehr on ftest duration 1h replication 1 default")
# -*- coding: utf-8 -*- ''' Created on 2017-10-25 10:54:53 RabbitMQ工具 @author: zhoujiagen ''' import pika # 定义连接参数 credentials = pika.PlainCredentials('zhoujiagen', 'zhoujiagen') conn_params = pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/spike', credentials=credentials) def BlockingConnection(connection_params): """ :param pika.ConnectionParameters connection_params: 连接参数 """ return pika.BlockingConnection(connection_params) def get_channel(conn): """ :param blocking_connection.BlockingConnection conn: 连接 :rtype: pika.synchronous_connection.BlockingChannel """ return conn.channel()
__author__ = "那位先生Beer" import pika credentials = pika.PlainCredentials('qkq', 'qkq6988751') connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.98.128', 5672, '/', credentials)) channel = connection.channel() channel.queue_declare(queue='hello3', durable=True) #queue = 'hello'队列名字,durable = True队列持久化,但是不能使消息持久化 channel.basic_publish( exchange='', #exchange的类型决定了发送消息的类型,决定了哪些queue符合接受类型 routing_key='hello3', #hello2 不是队列持久化,更改时需注意 body='Hello World!', properties=pika.BasicProperties(delivery_mode=2 #使消息持久化 )) print("[x] Sent 'Hello World!'") connection.close()
@File : consumer.py @Author : HaoQiangJian @Site : @Time : 18-11-13 下午5:27 @Version : """ import pika, time, json from ..config import MQ_HOST, MQ_PORT, MQ_USR, MQ_PWD, CRON_TIMES consumer = pika.BlockingConnection( pika.ConnectionParameters(host=MQ_HOST, port=MQ_PORT, virtual_host='/', credentials=pika.PlainCredentials( MQ_USR, MQ_PWD))) # 创建socket连接 channel = consumer.channel() # 创建管道 # channel.exchange_declare(exchange='order-exchange', exchange_type='topic') channel.exchange_declare(exchange='order-exchange', durable=True, exchange_type='topic') channel.queue_declare(queue='order-queue', durable=True) channel.queue_bind(exchange='order-exchange', queue='order-queue', routing_key='order.*') def add(x, y): return x + y
#!/usr/bin/env python import pika import time from testMail import Send credentials = pika.PlainCredentials('guest', 'guest') connection = pika.BlockingConnection( pika.ConnectionParameters('localhost', 5672, '/', credentials)) channel = connection.channel() channel.queue_declare(queue='mail', durable=False) print(' [*] Waiting for messages. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] Received %r" % body) send = Send() info = eval(body) send.send(info['subject'], info['content']) time.sleep(body.count(b'.')) print(" [x] Done") ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue='mail', on_message_callback=callback) channel.start_consuming()
#!/usr/bin/env python import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='<IP>', credentials=pika.PlainCredentials( username='******', password='******'))) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print("[x] Received %r" % body) channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
import pika import json import sys credentials = pika.PlainCredentials('sgatest', 'L3tm3t38t') parameters = pika.ConnectionParameters('149.165.168.247', 5672, '/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='sga.simple.python') def callback(ch, method, properties, body): print(" [x] Received %r" % body) str = body.decode('utf-8') print(str) reqObj = json.loads(str) reqObj['text'] = reqObj['text'] + ":InPython" msg = json.dumps(reqObj, ensure_ascii=False) channelClnt = connection.channel() channel.queue_declare(queue='sga.simple.java') channel.basic_publish(exchange='', routing_key='sga.simple.java', body=msg) print(" [x] Sent:") print(msg) channel.basic_consume(callback, queue='sga.simple.python', no_ack=True)
config_path = os.path.realpath(sys.path[0] + '/') config = ConfigParser.RawConfigParser() file_path = config_path + '/config.cfg' config.read(file_path) # Give the RabbitMQ docker a few seconds to start time.sleep(5) parameters = pika.ConnectionParameters( host=config.get('amqp', 'host'), port=config.get('amqp', 'port'), ssl=False, virtual_host=config.get('amqp', 'vhost'), credentials=pika.PlainCredentials( config.get('amqp', 'user'), config.get('amqp', 'password') ), connection_attempts=5, retry_delay=5 ) connection = pika.BlockingConnection(parameters) channel = connection.channel(1) channel.exchange_declare( exchange=config.get('amqp', 'exchange'), exchange_type=config.get('amqp', 'exchange_type'), passive=False, durable=True, auto_delete=False ) result = channel.queue_declare()
import pika import time from random import randrange credentials = pika.PlainCredentials('admin', 'admin') connection = pika.BlockingConnection( pika.ConnectionParameters(host='rabbitmq1', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) time.sleep(randrange(0, 5)) print(" [x] ERROR") ch.basic_nack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume('hello', callback) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
# @File : MQ_consume.py # @Software: PyCharm import time import json import sys import pika import httplib import Config as conf, DBHandler as db from LogUtils import Logger reload(sys) sys.setdefaultencoding('utf-8') logger = Logger() credentials = pika.PlainCredentials(conf.MQ_USERNAME,conf.MQ_PWD) connection = pika.BlockingConnection(pika.ConnectionParameters(conf.MQ_URL,5672,'/',credentials)) channel = connection.channel() channel.exchange_declare(exchange=conf.MQ_exchange, exchange_type='direct') channel.queue_declare(queue=conf.MQ_QUEUE,durable=True) channel.queue_bind(exchange=conf.MQ_exchange, queue=conf.MQ_QUEUE) print '==============================================================\n' print ' rabbtiMQ server: %s '%conf.MQ_URL print ' rabbtiMQ exchange: %s '%conf.MQ_exchange print ' rabbtiMQ queue: %s '%conf.MQ_QUEUE def callback(ch, method, properties, body): logger.info(" [x] Received %r\n\n" % body) dict = json.loads(body)
# 生产者代码 import pika # 用户名和密码 credentials = pika.PlainCredentials('guest', 'hUN7e4_1') # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。 parameters = pika.ConnectionParameters(host='server1', port=5672, virtual_host='/', credentials=credentials) # 阻塞方法 connection = pika.BlockingConnection(parameters) # 建立信道 channel = connection.channel() channel.exchange_declare(exchange='logs', exchange_type='fanout') message = 'send message to fanout' channel.basic_publish( exchange='logs', routing_key='', body=message, ) # 关闭与rabbitmq server的连接 connection.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import pika import requests from config import SERVER, conf if __name__ == "__main__": credentials = pika.PlainCredentials(SERVER['username'], SERVER['password']) parameters = pika.ConnectionParameters(SERVER['addr'], SERVER['port'], SERVER['path'], credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.exchange_declare('1c.fanout', exchange_type='fanout', durable=True) channel.queue_declare('tmall', passive=False, durable=True) channel.queue_bind('tmall', '1c.fanout') def get_products(): url = conf['share_data']['goods'] r = requests.get(url) if r.status_code == 200: return r.content raise Exception data = get_products() channel.basic_publish(exchange='1c.fanout', routing_key='', body=data) print " [x] Sent" connection.close()
import pika, json creds_broker = pika.PlainCredentials("rpc_user", "rpcme") conn_params = pika.ConnectionParameters("localhost", virtual_host="/", credentials=creds_broker) conn_broker = pika.BlockingConnection(conn_params) channel = conn_broker.channel() channel.exchange_declare(exchange="rpc", exchange_type="direct", auto_delete=False) channel.queue_declare(queue="ping", auto_delete=False) channel.queue_bind(queue="ping", exchange="rpc", routing_key="ping") def api_ping(channel, method, header, body): """Ping API call.""" channel.basic_ack(delivery_tag=method.delivery_tag) msg_dict = json.loads(body) print "Received API call...replying..." channel.basic_publish(body="Pong!" + str(msg_dict["time"]), exchange="", routing_key=header.reply_to) channel.basic_consume(api_ping, queue="ping", consumer_tag="ping") print "Waiting for RPC calls..." channel.start_consuming()
}) properties.content_type = 'text/json' ch.basic_publish(properties=properties, exchange='plugins-out', routing_key=method.routing_key, body=data) ch.basic_ack(delivery_tag=method.delivery_tag) connection = pika.BlockingConnection( pika.ConnectionParameters(host=RABBITMQ_HOST, port=RABBITMQ_PORT, virtual_host=BEEHIVE_DEPLOYMENT, credentials=pika.PlainCredentials( username=RABBITMQ_USERNAME, password=RABBITMQ_PASSWORD, ), connection_attempts=10, retry_delay=3.0)) channel = connection.channel() plugin = 'gps:1' channel.queue_declare(queue=plugin, durable=True) channel.queue_bind(queue=plugin, exchange='plugins-in', routing_key=plugin) channel.basic_consume(callback, queue=plugin, no_ack=False) channel.start_consuming()