| 1 |
.. _broker-kafka: |
| 2 |
|
| 3 |
============= |
| 4 |
Using Kafka |
| 5 |
============= |
| 6 |
|
| 7 |
.. _broker-Kafka-installation: |
| 8 |
|
| 9 |
Configuration |
| 10 |
============= |
| 11 |
|
| 12 |
For celeryconfig.py: |
| 13 |
|
| 14 |
.. code-block:: python |
| 15 |
|
| 16 |
import os |
| 17 |
|
| 18 |
task_serializer = 'json' |
| 19 |
broker_transport_options = { |
| 20 |
# "allow_create_topics": True, |
| 21 |
} |
| 22 |
broker_connection_retry_on_startup = True |
| 23 |
|
| 24 |
# For using SQLAlchemy as the backend |
| 25 |
# result_backend = 'db+postgresql://postgres:example@localhost/postgres' |
| 26 |
|
| 27 |
broker_transport_options.update({ |
| 28 |
"security_protocol": "SASL_SSL", |
| 29 |
"sasl_mechanism": "SCRAM-SHA-512", |
| 30 |
}) |
| 31 |
sasl_username = os.environ["SASL_USERNAME"] |
| 32 |
sasl_password = os.environ["SASL_PASSWORD"] |
| 33 |
broker_url = f"confluentkafka://{sasl_username}:{sasl_password}@broker:9094" |
| 34 |
broker_transport_options.update({ |
| 35 |
"kafka_admin_config": { |
| 36 |
"sasl.username": sasl_username, |
| 37 |
"sasl.password": sasl_password, |
| 38 |
}, |
| 39 |
"kafka_common_config": { |
| 40 |
"sasl.username": sasl_username, |
| 41 |
"sasl.password": sasl_password, |
| 42 |
"security.protocol": "SASL_SSL", |
| 43 |
"sasl.mechanism": "SCRAM-SHA-512", |
| 44 |
"bootstrap.servers": "broker:9094", |
| 45 |
} |
| 46 |
}) |
| 47 |
|
| 48 |
Please note that "allow_create_topics" is needed if the topic does not exist |
| 49 |
yet but is not necessary otherwise. |
| 50 |
|
| 51 |
For tasks.py: |
| 52 |
|
| 53 |
.. code-block:: python |
| 54 |
|
| 55 |
from celery import Celery |
| 56 |
|
| 57 |
app = Celery('tasks') |
| 58 |
app.config_from_object('celeryconfig') |
| 59 |
|
| 60 |
|
| 61 |
@app.task |
| 62 |
def add(x, y): |
| 63 |
return x + y |
| 64 |
|
| 65 |
Auth |
| 66 |
==== |
| 67 |
|
| 68 |
See above. The SASL username and password are passed in as environment variables. |
| 69 |
|
| 70 |
Further Info |
| 71 |
============ |
| 72 |
|
| 73 |
Celery queues get routed to Kafka topics. For example, if a queue is named "add_queue", |
| 74 |
then a topic named "add_queue" will be created/used in Kafka. |
| 75 |
|
| 76 |
For canvas, when using a backend that supports it, the typical mechanisms like |
| 77 |
chain, group, and chord seem to work. |
| 78 |
|
| 79 |
|
| 80 |
Limitations |
| 81 |
=========== |
| 82 |
|
| 83 |
Currently, using Kafka as a broker means that only one worker can be used. |
| 84 |
See https://github.com/celery/kombu/issues/1785. |