|
| 1 | +# |
| 2 | +# Copyright Kroxylicious Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | +# |
| 6 | +from typing import AnyStr |
| 7 | + |
| 8 | +from confluent_kafka import Consumer, KafkaException |
| 9 | +import argparse |
| 10 | +import sys |
| 11 | +import logging |
| 12 | +import json |
| 13 | +import inspect |
| 14 | + |
| 15 | +def get_value_from_type(obj): |
| 16 | + value_str = obj |
| 17 | + if isinstance(obj, bytes): |
| 18 | + value_str = obj.decode("utf-8") |
| 19 | + if isinstance(obj, list): |
| 20 | + value_str = [get_value_from_type(x) for x in obj] |
| 21 | + if isinstance(obj, tuple): |
| 22 | + value_str = { "Key" : str(get_value_from_type(obj[0])), |
| 23 | + "Value": str(get_value_from_type(obj[1])) } |
| 24 | + |
| 25 | + return value_str |
| 26 | + |
| 27 | +def props(obj): |
| 28 | + pr = {} |
| 29 | + for name in dir(obj): |
| 30 | + value = getattr(obj, name) |
| 31 | + if (not (name.startswith('__') or name.startswith("set_")) |
| 32 | + and not inspect.ismethod(value)): |
| 33 | + pr[name] = get_value_from_type(value()) |
| 34 | + return pr |
| 35 | + |
| 36 | +def print_record_json(msg): |
| 37 | + res = json.dumps(props(msg)) |
| 38 | + print("Received: " + res) |
| 39 | + |
| 40 | +def main(args): |
| 41 | + topic = args.topic |
| 42 | + records_expected = int(args.num_of_records) |
| 43 | + |
| 44 | + # Consumer configuration |
| 45 | + # See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md |
| 46 | + consumer_conf = {'bootstrap.servers': args.bootstrap_servers, 'group.id': args.group, 'session.timeout.ms': 6000, |
| 47 | + 'auto.offset.reset': 'earliest', 'enable.auto.offset.store': False} |
| 48 | + |
| 49 | + vargs = vars(args) |
| 50 | + extra_configuration = [x[0].split('=') for x in vargs.get('extra_conf', [])] |
| 51 | + consumer_conf.update(dict(extra_configuration)) |
| 52 | + |
| 53 | + # Create logger for consumer (logs will be emitted when poll() is called) |
| 54 | + logger = logging.getLogger('consumer') |
| 55 | + logger.setLevel(logging.DEBUG) |
| 56 | + handler = logging.StreamHandler() |
| 57 | + handler.setFormatter(logging.Formatter('%(asctime)-15s %(levelname)-8s %(message)s')) |
| 58 | + logger.addHandler(handler) |
| 59 | + |
| 60 | + # Create Consumer instance |
| 61 | + # Hint: try debug='fetch' to generate some log records |
| 62 | + c = Consumer(consumer_conf, logger=logger) |
| 63 | + |
| 64 | + def print_assignment(consumer, partitions): |
| 65 | + print('Assignment:', partitions) |
| 66 | + |
| 67 | + # Subscribe to topics |
| 68 | + c.subscribe([topic], on_assign=print_assignment) |
| 69 | + |
| 70 | + # Read records from Kafka, print to stdout |
| 71 | + try: |
| 72 | + records_received = 0 |
| 73 | + while True: |
| 74 | + msg = c.poll(timeout=1.0) |
| 75 | + if msg is None: |
| 76 | + continue |
| 77 | + if msg.error(): |
| 78 | + raise KafkaException(msg.error()) |
| 79 | + else: |
| 80 | + print_record_json(msg) |
| 81 | + # Store the offset associated with msg to a local cache. |
| 82 | + # Stored offsets are committed to Kafka by a background thread every 'auto.commit.interval.ms'. |
| 83 | + # Explicitly storing offsets after processing gives at-least once semantics. |
| 84 | + c.store_offsets(msg) |
| 85 | + records_received += 1 |
| 86 | + if records_received == records_expected: |
| 87 | + c.close() |
| 88 | + sys.exit(0) |
| 89 | + |
| 90 | + except KeyboardInterrupt: |
| 91 | + sys.stderr.write('%% Aborted by user\n') |
| 92 | + |
| 93 | + finally: |
| 94 | + # Close down consumer to commit final offsets. |
| 95 | + c.close() |
| 96 | + |
| 97 | +if __name__ == '__main__': |
| 98 | + parser = argparse.ArgumentParser(description="Consumer") |
| 99 | + parser.add_argument('-b', dest="bootstrap_servers", required=True, |
| 100 | + help="Bootstrap broker(s) (host[:port])") |
| 101 | + parser.add_argument('-n', dest="num_of_records", default=0, |
| 102 | + help="Number of records expected") |
| 103 | + parser.add_argument('-t', dest="topic", required=True, |
| 104 | + help="Topic name") |
| 105 | + parser.add_argument('-g', dest="group", default="test_group", |
| 106 | + help="Consumer group") |
| 107 | + parser.add_argument('-X', nargs=1, dest='extra_conf', action='append', help='Configuration property', default=[]) |
| 108 | + |
| 109 | + main(parser.parse_args()) |
0 commit comments