No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

64 líneas
2.2KB

  1. import logging
  2. import pickle
  3. try:
  4. import kafka
  5. except ImportError:
  6. kafka = None
  7. from .pubsub_manager import PubSubManager
  8. logger = logging.getLogger('socketio')
  9. class KafkaManager(PubSubManager): # pragma: no cover
  10. """Kafka based client manager.
  11. This class implements a Kafka backend for event sharing across multiple
  12. processes.
  13. To use a Kafka backend, initialize the :class:`Server` instance as
  14. follows::
  15. url = 'kafka://hostname:port'
  16. server = socketio.Server(client_manager=socketio.KafkaManager(url))
  17. :param url: The connection URL for the Kafka server. For a default Kafka
  18. store running on the same host, use ``kafka://``.
  19. :param channel: The channel name (topic) on which the server sends and
  20. receives notifications. Must be the same in all the
  21. servers.
  22. :param write_only: If set ot ``True``, only initialize to emit events. The
  23. default of ``False`` initializes the class for emitting
  24. and receiving.
  25. """
  26. name = 'kafka'
  27. def __init__(self, url='kafka://localhost:9092', channel='socketio',
  28. write_only=False):
  29. if kafka is None:
  30. raise RuntimeError('kafka-python package is not installed '
  31. '(Run "pip install kafka-python" in your '
  32. 'virtualenv).')
  33. super(KafkaManager, self).__init__(channel=channel,
  34. write_only=write_only)
  35. self.kafka_url = url[8:] if url != 'kafka://' else 'localhost:9092'
  36. self.producer = kafka.KafkaProducer(bootstrap_servers=self.kafka_url)
  37. self.consumer = kafka.KafkaConsumer(self.channel,
  38. bootstrap_servers=self.kafka_url)
  39. def _publish(self, data):
  40. self.producer.send(self.channel, value=pickle.dumps(data))
  41. self.producer.flush()
  42. def _kafka_listen(self):
  43. for message in self.consumer:
  44. yield message
  45. def _listen(self):
  46. for message in self._kafka_listen():
  47. if message.topic == self.channel:
  48. yield pickle.loads(message.value)