KafkaConsumer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace app\command;
  3. use think\console\Command;
  4. use think\console\Input;
  5. use think\console\Output;
  6. use app\common\library\Kafka;
  7. use think\Log;
  8. class KafkaConsumer extends Command
  9. {
  10. protected function configure()
  11. {
  12. $this->setName('kafka:consume')
  13. ->setDescription('Kafka consumer command');
  14. }
  15. protected function execute(Input $input, Output $output)
  16. {
  17. $output->writeln('Starting Kafka consumer...');
  18. try {
  19. $kafka = Kafka::getInstance();
  20. $topics = ['new_sdk_topic'];
  21. $kafka->consume($topics, function($message) use ($output) {
  22. $data = json_decode($message->payload, true);
  23. // 记录消息到日志
  24. Log::info('Received Kafka message: ' . $message->payload);
  25. // 输出消息到控制台
  26. $output->writeln(sprintf(
  27. "Received message:\nTopic: %s\nPartition: %s\nOffset: %s\nKey: %s\nPayload: %s\n",
  28. $message->topic_name,
  29. $message->partition,
  30. $message->offset,
  31. $message->key,
  32. $message->payload
  33. ));
  34. // 这里可以添加具体的业务处理逻辑
  35. switch ($data['event']) {
  36. case 'test_event':
  37. $output->writeln('Processing test event...');
  38. break;
  39. case 'custom_event':
  40. $output->writeln('Processing custom event...');
  41. break;
  42. default:
  43. $output->writeln('Processing unknown event...');
  44. }
  45. });
  46. } catch (\Exception $e) {
  47. $output->writeln('<error>Error: ' . $e->getMessage() . '</error>');
  48. Log::error('Kafka consumer error: ' . $e->getMessage());
  49. }
  50. }
  51. }