File tree Expand file tree Collapse file tree 4 files changed +25
-3
lines changed Expand file tree Collapse file tree 4 files changed +25
-3
lines changed Original file line number Diff line number Diff line change @@ -110,6 +110,15 @@ for more details.
110
110
>>> for i in range (1000 ):
111
111
... producer.send(' foobar' , b ' msg %d ' % i)
112
112
113
+ Thread safety
114
+ *************
115
+
116
+ The KafkaProducer can be used across threads without issue, unlike the
117
+ KafkaConsumer which cannot.
118
+
119
+ While it is possible to use the KafkaConsumer in a thread-local manner,
120
+ multiprocessing is recommended.
121
+
113
122
Compression
114
123
***********
115
124
Original file line number Diff line number Diff line change @@ -109,6 +109,16 @@ client. See `KafkaProducer <apidoc/KafkaProducer.html>`_ for more details.
109
109
... producer.send(' foobar' , b ' msg %d ' % i)
110
110
111
111
112
+ Thread safety
113
+ *************
114
+
115
+ The KafkaProducer can be used across threads without issue, unlike the
116
+ KafkaConsumer which cannot.
117
+
118
+ While it is possible to use the KafkaConsumer in a thread-local manner,
119
+ multiprocessing is recommended.
120
+
121
+
112
122
Compression
113
123
***********
114
124
Original file line number Diff line number Diff line change 1
1
#!/usr/bin/env python
2
2
import threading , logging , time
3
+ import multiprocessing
3
4
4
5
from kafka import KafkaConsumer , KafkaProducer
5
6
@@ -16,7 +17,7 @@ def run(self):
16
17
time .sleep (1 )
17
18
18
19
19
- class Consumer (threading . Thread ):
20
+ class Consumer (multiprocessing . Process ):
20
21
daemon = True
21
22
22
23
def run (self ):
@@ -29,12 +30,12 @@ def run(self):
29
30
30
31
31
32
def main ():
32
- threads = [
33
+ tasks = [
33
34
Producer (),
34
35
Consumer ()
35
36
]
36
37
37
- for t in threads :
38
+ for t in tasks :
38
39
t .start ()
39
40
40
41
time .sleep (10 )
Original file line number Diff line number Diff line change @@ -33,6 +33,8 @@ class KafkaConsumer(six.Iterator):
33
33
to allow multiple consumers to load balance consumption of topics (requires
34
34
kafka >= 0.9.0.0).
35
35
36
+ The consumer is not thread safe and should not be shared across threads.
37
+
36
38
Arguments:
37
39
*topics (str): optional list of topics to subscribe to. If not set,
38
40
call :meth:`~kafka.KafkaConsumer.subscribe` or
You can’t perform that action at this time.
0 commit comments