Use Apache Kafka With Laravel

Packages

September 21st, 2021

laravel-kafka-featured.png

Laravel Kafka is a package for using Apache Kafka producers and consumers in your Laravel app with ease. Using the publishOn method, you can fluently configure and publish message payloads:

1use Junges\Kafka\Facades\Kafka;
2 
3Kafka::publishOn('broker', 'topic')
4 ->withConfigOption('property-name', 'property-value')
5 ->withConfigOptions([
6 'property-name' => 'property-value'
7 ]);

Here's an example of how you send a message to Kafka via this package in a Laravel app:

1use Junges\Kafka\Facades\Kafka;
2 
3/** @var \Junges\Kafka\Producers\ProducerBuilder $producer */
4$producer = Kafka::publishOn('broker', 'topic')
5 ->withConfigOptions(['key' => 'value'])
6 ->withKafkaKey('your-kafka-key')
7 ->withKafkaKey('kafka-key')
8 ->withHeaders(['header-key' => 'header-value']);
9 
10$producer->send();

And here's an example of subscribing to messages via a consumer:

1use Junges\Kafka\Facades\Kafka;
2 
3$consumer = Kafka::createConsumer('broker')->subscribe('topic');
4 
5// Handler via callback:
6$consumer->withHandler(function(\RdKafka\Message $message) {
7 // Handle your message here
8});
9 
10// Invokable handler:
11class Handler
12{
13 public function __invoke(\RdKafka\Message $message){
14 // Handle your message here
15 }
16}
17 
18$consumer->withHandler(Handler::class)

Other features this package provides as found in the readme:

  • Configure max messages to be consumed
  • Configure a Dead letter queue - Wikipedia
  • Configure middleware
  • Kafka::fake() method for faking a Kafka producer in tests
  • Method to enable debugging during development
  • Configurable message payloads

Under-the-hood, this package requires the rdkafka extension, which provides a production-ready, fast Kafka client for PHP. You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.