Message handlers

Now that you have created your kafka consumer, you must create a handler for the messages this consumer receives. By default, a consumer is any callable. You can use an invokable class or a simple callback. Use the withHandler method to specify your handler:

$consumer = \Junges\Kafka\Facades\Kafka::consumer();

// Using callback:
$consumer->withHandler(function(\Junges\Kafka\Contracts\ConsumerMessage $message, \Junges\Kafka\Contracts\MessageConsumer $consumer) {
    // Handle your message here
});

Or, using an invokable class:

class Handler
{
    public function __invoke(\Junges\Kafka\Contracts\ConsumerMessage $message, \Junges\Kafka\Contracts\MessageConsumer $consumer) {
        // Handle your message here
    }
}

$consumer = \Junges\Kafka\Facades\Kafka::consumer()->withHandler(new Handler)

The ConsumerMessage contract gives you some handy methods to get the message properties:

  • getKey(): Returns the Kafka Message Key
  • getTopicName(): Returns the topic where the message was published
  • getPartition(): Returns the kafka partition where the message was published
  • getHeaders(): Returns the kafka message headers
  • getBody(): Returns the body of the message
  • getOffset(): Returns the offset where the message was published

Support Laravel Kafka by sponsoring me!

Do you find Laravel Kafka valuable and wanna support its development?

Laravel Kafka is free and Open Source software, built to empower developers like you. Your support helps maintain and enhance the project. If you find it valuable, please consider sponsoring me on GitHub. Every contribution makes a difference and keeps the development going strong! Thank you!

Want to hide this message? Sponsor at any tier of $10/month or more!
Previous
Consumer groups