3

Laravel 扩展推荐:Apache Kafka

 2 years ago
source link: https://zhuanlan.zhihu.com/p/414825064
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel 扩展推荐:Apache Kafka

摈弃世俗浮躁,追求技术精湛

转载自 Laravel 论坛:https://learnku.com/laravel/t/61072

Laravel Kafka 让你在 Laravel 应用中使用 Apache Kafka 生产者和消费者变得简单。使用 publishOn 方法,可流畅地进行配置和发布消息:

use Junges\Kafka\Facades\Kafka;

Kafka::publishOn('broker', 'topic')
    ->withConfigOption('property-name', 'property-value')
    ->withConfigOptions([
        'property-name' => 'property-value'
    ]);

下面展示如何通过这个包在 Laravel 应用中向 Kafka 发送消息:

use Junges\Kafka\Facades\Kafka;

/** @var \Junges\Kafka\Producers\ProducerBuilder $producer */
$producer = Kafka::publishOn('broker', 'topic')
    ->withConfigOptions(['key' => 'value'])
    ->withKafkaKey('your-kafka-key')
    ->withKafkaKey('kafka-key')
    ->withHeaders(['header-key' => 'header-value']);

$producer->send();

这里是消费者订阅消息的示例:

use Junges\Kafka\Facades\Kafka;

$consumer = Kafka::createConsumer('broker')->subscribe('topic');

// 通过回调函数处理:
$consumer->withHandler(function(\RdKafka\Message $message) {
    // 消息处理
});

// Invokable handler:
class Handler
{
    public function __invoke(\RdKafka\Message $message){
        //消息处理
    }
}

$consumer->withHandler(Handler::class)

这个包的其他功能请见 readme:

  • 最大消息消费数量配置
  • 死信队列 - 维基百科 配置
  • 中间件配置
  • 在测试中使用 Kafka::fake() 方法模拟 Kafka 生产者
  • 开发模式下开启调试
  • 消息体可配置

这个包依赖于 rdkafka PHP 原生扩展,Github 上有包详细的安装说明和 源码

讨论请前往专业的 Laravel 论坛:https://learnku.com/laravel/t/61072


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK