Kafka.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\common\library;
  3. use RdKafka\Conf;
  4. use RdKafka\Producer;
  5. use RdKafka\KafkaConsumer;
  6. use think\Config;
  7. class Kafka
  8. {
  9. private $config;
  10. private static $instance = null;
  11. private function __construct()
  12. {
  13. $this->config = Config::get('kafka.');
  14. }
  15. public static function getInstance()
  16. {
  17. if (self::$instance === null) {
  18. self::$instance = new self();
  19. }
  20. return self::$instance;
  21. }
  22. /**
  23. * 获取生产者实例
  24. */
  25. public function getProducer()
  26. {
  27. $conf = new Conf();
  28. $conf->set('metadata.broker.list', $this->config['bootstrap_servers']);
  29. if ($this->config['debug']) {
  30. $conf->set('debug', 'all');
  31. }
  32. return new Producer($conf);
  33. }
  34. /**
  35. * 获取消费者实例
  36. */
  37. public function getConsumer()
  38. {
  39. $conf = new Conf();
  40. $conf->set('metadata.broker.list', $this->config['bootstrap_servers']);
  41. $conf->set('group.id', $this->config['group_id']);
  42. $conf->set('auto.offset.reset', 'earliest');
  43. if ($this->config['debug']) {
  44. $conf->set('debug', 'all');
  45. }
  46. return new KafkaConsumer($conf);
  47. }
  48. /**
  49. * 发送消息
  50. */
  51. public function publish($topic, $message, $key = null)
  52. {
  53. $producer = $this->getProducer();
  54. $topic = $producer->newTopic($topic);
  55. $topic->produce(RD_KAFKA_PARTITION_UA, 0, json_encode($message), $key);
  56. $producer->flush(10000);
  57. }
  58. /**
  59. * 消费消息
  60. */
  61. public function consume($topics, callable $callback)
  62. {
  63. $consumer = $this->getConsumer();
  64. $consumer->subscribe($topics);
  65. while (true) {
  66. $message = $consumer->consume(120 * 1000);
  67. switch ($message->err) {
  68. case RD_KAFKA_RESP_ERR_NO_ERROR:
  69. $callback($message);
  70. break;
  71. case RD_KAFKA_RESP_ERR__PARTITION_EOF:
  72. echo "No more messages; will wait...\n";
  73. break;
  74. case RD_KAFKA_RESP_ERR__TIMED_OUT:
  75. echo "Timed out\n";
  76. break;
  77. default:
  78. throw new \Exception($message->errstr(), $message->err);
  79. }
  80. }
  81. }
  82. }