本文整理汇总了Python中kombu.BrokerConnection.channel方法的典型用法代码示例。如果您正苦于以下问题:Python BrokerConnection.channel方法的具体用法?Python BrokerConnection.channel怎么用?Python BrokerConnection.channel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kombu.BrokerConnection
的用法示例。
在下文中一共展示了BrokerConnection.channel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FanoutPublisher
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class FanoutPublisher(PluginBase):
def __init__(self):
if app.debug:
setup_logging(loglevel='DEBUG', loggers=[''])
self.connection = BrokerConnection(app.config['AMQP_URL'])
try:
self.connection.connect()
except Exception as e:
LOG.error('Failed to connect to AMQP transport %s: %s', app.config['AMQP_URL'], e)
raise RuntimeError
self.channel = self.connection.channel()
self.exchange_name = app.config['AMQP_TOPIC']
self.exchange = Exchange(name=self.exchange_name, type='fanout', channel=self.channel)
self.producer = Producer(exchange=self.exchange, channel=self.channel)
LOG.info('Configured fanout publisher on topic "%s"', app.config['AMQP_TOPIC'])
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
LOG.info('Sending message %s to AMQP topic "%s"', alert.get_id(), app.config['AMQP_TOPIC'])
LOG.debug('Message: %s', alert.get_body())
self.producer.publish(alert.get_body(), declare=[self.exchange], retry=True)
示例2: test_StdChannel
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class test_StdChannel(TestCase):
def setUp(self):
self.conn = BrokerConnection("memory://")
self.channel = self.conn.channel()
self.channel.queues.clear()
self.conn.connection.state.clear()
def test_Consumer(self):
q = Queue("foo")
print(self.channel.queues)
cons = self.channel.Consumer(q)
self.assertIsInstance(cons, Consumer)
self.assertIs(cons.channel, self.channel)
def test_Producer(self):
prod = self.channel.Producer()
self.assertIsInstance(prod, Producer)
self.assertIs(prod.channel, self.channel)
def test_interface_list_bindings(self):
with self.assertRaises(NotImplementedError):
StdChannel().list_bindings()
def test_interface_after_reply_message_received(self):
self.assertIsNone(StdChannel().after_reply_message_received(
Queue("foo")))
示例3: MqReader
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class MqReader(object):
def __init__(self, kwargs):
if kwargs:
self.kwargs = kwargs
else:
self.kwargs = MqDict
def connect(self, hostname="localhost", userid="guest", password="guest", virtual_host="/"):
self.conn = BrokerConnection(hostname, userid, password, virtual_host)
# define Web2Server exchange
exchange = Exchange(self.kwargs["X7_E"], type="direct")
queue = Queue(self.kwargs["X7_Q"], exchange, routing_key=self.kwargs["X7_RK"])
channel = self.conn.channel()
self.bound_queue = queue(channel)
# consumer = Consumer(channel, self.queue, callbacks=[self.callback])
# consumer.consume()
def get(self):
message = self.bound_queue.get()
if message is None:
return None
message.ack()
return message
示例4: MqServer
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class MqServer(object):
"""
exchange='E_X7_W2S', queue='Q_X7_W2S',routing_key = 'RK_X7_W2S'
"""
def __init__(self, callback, kwargs):
self.callback = callback
if kwargs:
self.kwargs = kwargs
else:
self.kwargs = MqDict
def connect(self, hostname="localhost", userid="guest", password="guest", virtual_host="/"):
self.conn = BrokerConnection(hostname, userid, password, virtual_host)
# define Web2Server exchange
exchange = Exchange(self.kwargs["X7_E"], type="direct")
self.queue = Queue(self.kwargs["X7_Q"], exchange, routing_key=self.kwargs["X7_RK"])
channel = self.conn.channel()
consumer = Consumer(channel, self.queue, callbacks=[self.callback])
consumer.consume()
def run(self, once=False):
if once:
self.conn.drain_events()
else:
while True:
self.conn.drain_events()
def get(self):
message = self.queue.get(block=True)
message.ack()
return message
示例5: main
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def main():
filename = "meta"
fptr = open(filename, "r")
amqpurl = fptr.readline().strip()
exchange_name = fptr.readline().strip()
exchange = Exchange(exchange_name, type="direct")
D_queue = Queue(exchange_name, exchange, routing_key=exchange_name, auto_delete=False, exclusive=False)
connection = BrokerConnection(amqpurl)
print amqpurl
channel = connection.channel()
queue = D_queue(channel)
queue.declare()
producer = Producer(channel, exchange, routing_key=exchange_name)
message_count = int(sys.argv[1])
imgsize = int(sys.argv[2])
name = sys.argv[3]
s3url = ""
if 'S3_URL' in os.environ:
s3url = os.environ['S3_URL']
s3id = os.environ['EC2_ACCESS_KEY']
s3pw = os.environ['EC2_SECRET_KEY']
n = datetime.now()
print "XXX starting %s" % (str(n))
msg_list = []
dashi_name = str(uuid.uuid4()).split('-')[0]
for i in range(0, message_count):
msg = {'program': 'python node2.py %d %d %d' % (i, message_count, imgsize),
'rank': i,
's3url': s3url,
's3id': s3id,
's3pw': s3pw,
'testname': name,
'dashiname': dashi_name}
msg_list.append(msg)
random.shuffle(msg_list)
print "Add the messages to the queue..."
for msg in msg_list:
print "%s %d of %d" % (msg['testname'], msg['rank'], message_count)
sys.stdout.flush()
producer.publish(msg,
exchange=exchange,
routing_key=exchange_name,
serializer="json")
dashi = get_dashi_connection(amqpurl, dashi_name)
p_con = get_phantom_con(s3id, s3pw)
wait_till_done(dashi, message_count, p_con, name)
n = datetime.now()
print "XXX done %s" % (str(n))
示例6: connect
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def connect(self, hostname="localhost", userid="guest", password="guest", virtual_host="/"):
conn = BrokerConnection(hostname, userid, password, virtual_host)
# define Web2Server exchange
exchange = Exchange(self.kwargs["X7_E"], type="direct")
# queue = Queue(self.kwargs["X7_Q"], exchange, routing_key=self.kwargs["X7_RK"])
channel = conn.channel()
self.producer = Producer(channel, exchange, routing_key=self.kwargs["X7_RK"])
示例7: KombuLogger
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class KombuLogger(object):
def __init__(self, host="localhost", user="guest", password="guest", vhost="/", exchange="analytics"):
self.connection = BrokerConnection(host, user, password, vhost)
self.channel = self.connection.channel()
self.exchange = Exchange(exchange, "topic", durable=True, auto_delete=False)
self.producer = Producer(self.channel, exchange=self.exchange, serializer="json")
def write(self, event, timestamp, attributes):
self.producer.publish({"event": event, "ts": timestamp, "attr": attributes}, routing_key=event)
示例8: exchange_send
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def exchange_send(data,exchange):
try:
connection = BrokerConnection()
channel = connection.channel()
producer = Producer(channel, Exchange(exchange, type="fanout"))
producer.publish(data)
channel.close()
connection.close()
except Exception, error:
print(error)
示例9: __init__
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class Audit:
def __init__(self, hostname='localhost', port='5672',
userid='', password='', virtual_host='graylog',
exchange=None):
self.hostname = hostname
self.port = port
self.userid = userid
self.password = password
self.virtual_host = virtual_host
self.connection = BrokerConnection(virtual_host=virtual_host)
self.exchange_setup = exchange or ExchangeSetup()
def custom_exchange(self, exchange, exchange_type, routing_key, queue):
"""Broker exchange can be set after the object has been instantiated.
Args:
exchange (str): Exchange name
exchange_type (str): AMQP exchange type, see your broker manual
routing_key (str)
queue (str)
"""
self.exchange_setup.exchange = exchange
self.exchange_setup.exchange_type = exchange_type
self.exchange_setup.routing_key = routing_key
self.exchange_setup.queue = queue
def log(self, message):
"""Pushes argument object to message broker.
Args:
message (json/gelp): Message can depend on third-party log software
Graylog uses gelp format: https://www.graylog.org/resources/gelf/
"""
if (type(message) is not str) or (message == ''):
print 'Unable to log empty message'
return False
if len(message) > 8192:
print 'Message size too large'
return False
self.connection.connect()
channel = self.connection.channel()
exchange = Exchange(self.exchange_setup.exchange,
type=self.exchange_setup.exchange_type)
bound_exchange = exchange(channel)
bound_exchange.declare()
# example_message = '{"short_message":"Kombu", "host":"example.org"}'
message = bound_exchange.Message(message)
bound_exchange.publish(message, routing_key=self.exchange_setup.routing_key)
self.connection.release()
示例10: _connect
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def _connect(glance_api_cfg):
# We use BrokerConnection rather than Connection as RHEL 6 has an ancient
# version of kombu library.
conn = BrokerConnection(hostname=glance_api_cfg['host'],
port=glance_api_cfg['port'],
userid=glance_api_cfg['userid'],
password=glance_api_cfg['password'],
virtual_host=glance_api_cfg['virtual_host'])
exchange = Exchange(glance_api_cfg['exchange'],
type='topic',
durable=False,
channel=conn.channel())
return conn, exchange
示例11: add_query
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def add_query(query):
query = query.lower()
queries = fetch_queries()
result = True
slots = getattr(settings, 'KRAL_SLOTS', 1)
if query in queries:
queries.remove(query)
else:
try:
connection = BrokerConnection();
channel = connection.channel();
Exchange(query, type="fanout")(channel).declare()
print('Exchange declared for: %s' % query)
except Exception,error:
print(error)
示例12: main
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def main():
cfg = {'hostname':'localhost', 'userid':'guest', 'password':'guest', 'virtual_host':'/', 'port':5672}
transport = 'pika'
#transport = 'librabbitmq'
connection = BrokerConnection(transport=transport, **cfg)
connection.connect()
cfg = {'name':'simple-test-1', 'auto_delete':True, 'durable':False, 'delivery_mode':'transient'}
channel = connection.channel()
exchange = Exchange(channel=channel, **cfg)
#exchange = exchange_def(channel)
routing_key = 'simple-test-1-route'
queue = Queue(exchange=exchange, routing_key=routing_key, **cfg)
channel = connection.channel()
producer = Producer(channel=channel, exchange=exchange, routing_key=routing_key)
channel = connection.channel()
consumer = Consumer(channel=channel, queues=[queue], callbacks=[receive])
consumer.consume()
def serve_forever():
while True:
#print 'drain'
#gevent.sleep(0.0001)
connection.drain_events(timeout=1)
def publish_forever():
while True:
producer.publish(loremIpsum)
gevent.sleep(0.0001)
#g1, g2 = gevent.spawn(publish_forever), gevent.spawn(serve_forever)
g2 = gevent.spawn(serve_forever)
g1 = gevent.spawn(publish_forever)
gevent.joinall([g1, g2])
示例13: test_Message
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class test_Message(TestCase):
def setUp(self):
self.conn = BrokerConnection("memory://")
self.channel = self.conn.channel()
self.message = Message(self.channel, delivery_tag=313)
def test_ack_respects_no_ack_consumers(self):
self.channel.no_ack_consumers = set(["abc"])
self.message.delivery_info["consumer_tag"] = "abc"
ack = self.channel.basic_ack = Mock()
self.message.ack()
self.assertNotEqual(self.message._state, "ACK")
self.assertFalse(ack.called)
def test_ack_missing_consumer_tag(self):
self.channel.no_ack_consumers = set(["abc"])
self.message.delivery_info = {}
ack = self.channel.basic_ack = Mock()
self.message.ack()
ack.assert_called_with(self.message.delivery_tag)
def test_ack_not_no_ack(self):
self.channel.no_ack_consumers = set()
self.message.delivery_info["consumer_tag"] = "abc"
ack = self.channel.basic_ack = Mock()
self.message.ack()
ack.assert_called_with(self.message.delivery_tag)
def test_ack_log_error_when_no_error(self):
ack = self.message.ack = Mock()
self.message.ack_log_error(Mock(), KeyError)
ack.assert_called_with()
def test_ack_log_error_when_error(self):
ack = self.message.ack = Mock()
ack.side_effect = KeyError("foo")
logger = Mock()
self.message.ack_log_error(logger, KeyError)
ack.assert_called_with()
self.assertTrue(logger.critical.called)
self.assertIn("Couldn't ack", logger.critical.call_args[0][0])
示例14: FanoutPublisher
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
class FanoutPublisher(PluginBase):
def __init__(self, name=None):
if app.config['DEBUG']:
setup_logging(loglevel='DEBUG', loggers=[''])
self.connection = BrokerConnection(AMQP_URL)
try:
self.connection.connect()
except Exception as e:
LOG.error('Failed to connect to AMQP transport %s: %s', AMQP_URL, e)
raise RuntimeError
self.channel = self.connection.channel()
self.exchange_name = AMQP_TOPIC
self.exchange = Exchange(name=self.exchange_name, type='fanout', channel=self.channel)
self.producer = Producer(exchange=self.exchange, channel=self.channel)
super(FanoutPublisher, self).__init__(name)
LOG.info('Configured fanout publisher on topic "%s"', AMQP_TOPIC)
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
LOG.info('Sending message %s to AMQP topic "%s"', alert.get_id(), AMQP_TOPIC)
try:
body = alert.serialize # alerta >= 5.0
# update body's datetime-related fields with utc-aware values
body.update({key: body[key].replace(tzinfo=pytz.utc) for key in ['createTime', 'lastReceiveTime', 'receiveTime']})
except Exception:
body = alert.get_body() # alerta < 5.0
LOG.debug('Message: %s', body)
self.producer.publish(body, declare=[self.exchange], retry=True)
def status_change(self, alert, status, text):
return
示例15: publish_cmd
# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import channel [as 别名]
def publish_cmd():
parser = get_parser("publish")
(options, args) = parser.parse_args(sys.argv[2:])
if len(args) < 1:
parser.error("You must provide a queue hostname to publish to!")
exchange = Exchange(options.exchange, type="fanout", delivery_mode="transient")
queue = Queue(options.queue, exchange)
connection = BrokerConnection(hostname=args[0],
userid=options.userid,
password=options.password,
virtual_host=options.vhost)
channel = connection.channel()
producer = Producer(channel, exchange)
pods = pod.load_pod_dir(dirname=options.directory,
timeout=options.timeout,
# The first arg is the queue hostname, the rest
# will be pod names
filter_fn=pod.get_pod_filter(options.pod))
pods.update(pod.get_barker_metadata())
producer.publish(pods, serializer="json")
return 0