|
1 | | -import logging |
| 1 | +#!/usr/bin/env python |
| 2 | +import threading, logging, time |
2 | 3 |
|
3 | | -from kafka.client import KafkaClient, FetchRequest, ProduceRequest |
| 4 | +from kafka.client import KafkaClient |
4 | 5 | from kafka.consumer import SimpleConsumer |
5 | 6 | from kafka.producer import SimpleProducer |
6 | 7 |
|
7 | | -def produce_example(client): |
8 | | - producer = SimpleProducer(client, "my-topic") |
9 | | - producer.send_messages("test") |
| 8 | +class Producer(threading.Thread): |
| 9 | + daemon = True |
10 | 10 |
|
11 | | -def consume_example(client): |
12 | | - consumer = SimpleConsumer(client, "test-group", "my-topic") |
13 | | - for message in consumer: |
14 | | - print(message) |
| 11 | + def run(self): |
| 12 | + client = KafkaClient("localhost:9092") |
| 13 | + producer = SimpleProducer(client) |
| 14 | + |
| 15 | + while True: |
| 16 | + producer.send_messages('my-topic', "test") |
| 17 | + producer.send_messages('my-topic', "\xc2Hola, mundo!") |
| 18 | + |
| 19 | + time.sleep(1) |
| 20 | + |
| 21 | + |
| 22 | +class Consumer(threading.Thread): |
| 23 | + daemon = True |
| 24 | + |
| 25 | + def run(self): |
| 26 | + client = KafkaClient("localhost:9092") |
| 27 | + consumer = SimpleConsumer(client, "test-group", "my-topic") |
| 28 | + |
| 29 | + for message in consumer: |
| 30 | + print(message) |
15 | 31 |
|
16 | 32 | def main(): |
17 | | - client = KafkaClient("localhost:9092") |
18 | | - produce_example(client) |
19 | | - consume_example(client) |
| 33 | + threads = [ |
| 34 | + Producer(), |
| 35 | + Consumer() |
| 36 | + ] |
| 37 | + |
| 38 | + for t in threads: |
| 39 | + t.start() |
| 40 | + |
| 41 | + time.sleep(5) |
20 | 42 |
|
21 | 43 | if __name__ == "__main__": |
22 | | - logging.basicConfig(level=logging.DEBUG) |
| 44 | + logging.basicConfig( |
| 45 | + format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s', |
| 46 | + level=logging.DEBUG |
| 47 | + ) |
23 | 48 | main() |
0 commit comments