m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.8 KiB

6 months ago
  1. from __future__ import absolute_import
  2. from itertools import cycle
  3. import logging
  4. import random
  5. from kafka.vendor.six.moves import xrange # pylint: disable=import-error
  6. from .base import Producer
  7. log = logging.getLogger(__name__)
  8. class SimpleProducer(Producer):
  9. """A simple, round-robin producer.
  10. See Producer class for Base Arguments
  11. Additional Arguments:
  12. random_start (bool, optional): randomize the initial partition which
  13. the first message block will be published to, otherwise
  14. if false, the first message block will always publish
  15. to partition 0 before cycling through each partition,
  16. defaults to True.
  17. """
  18. def __init__(self, *args, **kwargs):
  19. self.partition_cycles = {}
  20. self.random_start = kwargs.pop('random_start', True)
  21. super(SimpleProducer, self).__init__(*args, **kwargs)
  22. def _next_partition(self, topic):
  23. if topic not in self.partition_cycles:
  24. if not self.client.has_metadata_for_topic(topic):
  25. self.client.ensure_topic_exists(topic)
  26. self.partition_cycles[topic] = cycle(self.client.get_partition_ids_for_topic(topic))
  27. # Randomize the initial partition that is returned
  28. if self.random_start:
  29. num_partitions = len(self.client.get_partition_ids_for_topic(topic))
  30. for _ in xrange(random.randint(0, num_partitions-1)):
  31. next(self.partition_cycles[topic])
  32. return next(self.partition_cycles[topic])
  33. def send_messages(self, topic, *msg):
  34. partition = self._next_partition(topic)
  35. return super(SimpleProducer, self).send_messages(
  36. topic, partition, *msg
  37. )
  38. def __repr__(self):
  39. return '<SimpleProducer batch=%s>' % self.async