php对接kafka

生产者

<?php
class KafkaProducer
{
    public static $brokerList = '192.168.10.105:9092';

    public static function send($message, $topic)
    {
        self::producer($message, $topic);
    }

    public static function producer($message, $topic = 'ponhuhu')
    {
        $conf = new \RdKafka\Conf();
        $conf->set('metadata.broker.list', self::$brokerList);
        $producer = new \RdKafka\Producer($conf);
        $topic = $producer->newTopic($topic);
        $topic->produce(RD_KAFKA_PARTITION_UA, 0, json_encode($message));
        $producer->poll(0);
        $result = $producer->flush(10000);
        if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
            throw new \RuntimeException('Was unable to flush, messages might be lost!');
        }
    }
}

$kafka = new KafkaProducer();
$kafka::send('nihao!!!!!','ponhuhu');

消费者

<?php
class KafkaConsumer
{
    public static $brokerList = '192.168.10.105:9092';

    public static function consumer()
    {
        $conf = new \RdKafka\Conf();
        $conf->set('group.id', 'ponhu');
        $rk = new \RdKafka\Consumer($conf);
        $rk->addBrokers("192.168.10.105");
        $topicConf = new \RdKafka\TopicConf();
        $topicConf->set('auto.commit.interval.ms', 100);
        $topicConf->set('offset.store.method', 'broker');
        $topicConf->set('auto.offset.reset', 'smallest');
        $topic = $rk->newTopic('ponhu', $topicConf);
        $topic->consumeStart(0, RD_KAFKA_OFFSET_STORED);
        while (true) {
            $message = $topic->consume(0, 120*10000);
            switch ($message->err) {
                case RD_KAFKA_RESP_ERR_NO_ERROR:
                    var_dump($message);

                    break;
                case RD_KAFKA_RESP_ERR__PARTITION_EOF:
                    echo "No more messages; will wait for more\n";
                    break;
                case RD_KAFKA_RESP_ERR__TIMED_OUT:
                    echo "Timed out\n";
                    break;
                default:
                    throw new \Exception($message->errstr(), $message->err);
                    break;
            }
        }
    }
}

$kafka = new KafkaConsumer();
$kafka::consumer();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值