When I change the "direct" type to "fanout" or "topic", it is work.But the "direct" type is not work.
- I wrote according to the example of the official website.
- And I tried deleting the code => "from future import absolute_import, unicode_literals".But it still not work.
- queues.py
- it is work if I change type to 'fanout' or 'topic'.
from __future__ import absolute_import, unicode_literals
from kombu import Queue, Exchange
exchange = Exchange('demo_exchange', type='topic')
demo_queues = [
Queue('one', exchange, routing_key='o'),
Queue('two', exchange, routing_key='t'),
Queue('three', exchange, routing_key='th'),
]
- worker.py
from __future__ import absolute_import, unicode_literals
from kombu.mixins import ConsumerMixin
from kombu import Connection
from queues import demo_queues
class Worker(ConsumerMixin):
def __init__(self, connection):
self.connection = connection
def get_consumers(self, Consumer, channel):
return [Consumer(queues=demo_queues, accept=['pickle', 'json'], callbacks=[self.on_task])]
def on_task(self, body, message):
args = body['args']
func = body['func']
print(args, func)
func()
message.ack()
if __name__ == '__main__':
with Connection('redis://localhost:6379/0') as conn:
try:
worker = Worker(conn)
worker.run()
except KeyboardInterrupt:
print('bye')
- client.py
from __future__ import absolute_import, unicode_literals
from kombu.pools import producers
from queues import exchange
priority_to_routing_key = {
'high': 'o',
'mid': 't',
'low': 'th',
}
def send_tasks(conn, func, args, priority='high'):
data = {'func': func, 'args': args}
with producers[conn].acquire(block=True) as producer:
routing_key = priority_to_routing_key[priority]
producer.publish(data,
serializer='pickle',
exchange=exchange,
declare=[exchange],
routing_key=routing_key)
if __name__ == '__main__':
from kombu import Connection
from tasks import func_task
connection = Connection('redis://localhost:6379/0')
send_tasks(connection, func=func_task, args=('test hello'), priority='mid')
- tasks.py
def func_task(n='hello'):
print(n, '---====')
I hope to work out this.