PHP中使用kafka

Kafka是为分布式高吞吐量系统设计的。Kafka可以很好地替代传统的消息队列。与其他消息传递系统相比,Kafka具有更好的吞吐量、内置的分区、复制和固有的容错性,这使它非常适合于大型消息处理应用程序。

在PHP中使用Kafka首先需要安装php-kafka扩展,请参考这里进行安装。

下面是PHP使用kakfa的Demo。

<?php

$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');

//If you need to produce exactly once and want to keep the original produce order, uncomment the line below
//$conf->set('enable.idempotence', 'true');

$producer = new RdKafka\Producer($conf);

$topic = $producer->newTopic("test");

for ($i = 0; $i < 10; $i++) {
    $topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message $i");
    $producer->poll(0);
}

for ($flushRetries = 0; $flushRetries < 10; $flushRetries++) {
    $result = $producer->flush(10000);
    if (RD_KAFKA_RESP_ERR_NO_ERROR === $result) {
        break;
    }
}

if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
    throw new \RuntimeException('Was unable to flush, messages might be lost!');
}

?>
Supervisord进程管理工具
PHP网址缩短: Url Shortener
ajax-loader