kafka-php
kafka-php
kafka-php的github地址 https://github.com/jacky5059/kafka-php
生产者produce示例代码
<?php
set_include_path(
implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../lib'),
get_include_path(),
))
);
require 'autoloader.php';
$host = 'localhost';
$port = 9092;
$topic = 'test';
$producer = new Kafka_Producer($host, $port, Kafka_Encoder::COMPRESSION_NONE);
$in = fopen('php://stdin', 'r');
while (true) {
echo "\nEnter comma separated messages:\n";
$messages = explode(',', fgets($in));
foreach (array_keys($messages) as $k) {
//$messages[$k] = trim($messages[$k]);
}
$bytes = $producer->send($messages, $topic);
printf("\nSuccessfully sent %d messages (%d bytes)\n\n", count($messages), $bytes);
}
简单消费者simple consumer示例代码
<?php
set_include_path(
implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../lib'),
get_include_path(),
))
);
require 'autoloader.php';
$host = 'localhost';
$zkPort = 2181; //zookeeper
$kPort = 9092; //kafka server
$topic = 'test';
$maxSize = 10000000;
$socketTimeout = 2;
$offset = 0;
$partition = 0;
$nMessages = 0;
$consumer = new Kafka_SimpleConsumer($host, $kPort, $socketTimeout, $maxSize);
while (true) {
try {
//create a fetch request for topic "test", partition 0, current offset and fetch size of 1MB
$fetchRequest = new Kafka_FetchRequest($topic, $partition, $offset, $maxSize);
//get the message set from the consumer and print them out
$partialOffset = 0;
$messages = $consumer->fetch($fetchRequest);
foreach ($messages as $msg) {
++$nMessages;
echo "\nconsumed[$offset][$partialOffset][msg #{$nMessages}]: " . $msg->payload();
$partialOffset = $messages->validBytes();
}
//advance the offset after consuming each message
$offset += $messages->validBytes();
//echo "\n---[Advancing offset to $offset]------(".date('H:i:s').")";
unset($fetchRequest);
//sleep(2);
} catch (Exception $e) {
// probably consumed all items in the queue.
echo "\nERROR: " . get_class($e) . ': ' . $e->getMessage()."\n".$e->getTraceAsString()."\n";
sleep(2);
}
}
基于zookeeper的消费者zkconsumer示例代码
<?php
set_include_path(
implode(PATH_SEPARATOR, array(
realpath(__DIR__ . '/../lib'),
get_include_path(),
))
);
require 'autoloader.php';
// zookeeper address (one or more, separated by commas)
$zkaddress = 'localhost:8121';
// kafka topic to consume from
$topic = 'testtopic';
// kafka consumer group
$group = 'testgroup';
// socket buffer size: must be greater than the largest message in the queue
$socketBufferSize = 10485760; //10 MB
// approximate max number of bytes to get in a batch
$maxBatchSize = 20971520; //20 MB
$zookeeper = new Zookeeper($zkaddress);
$zkconsumer = new Kafka_ZookeeperConsumer(
new Kafka_Registry_Topic($zookeeper),
new Kafka_Registry_Broker($zookeeper),
new Kafka_Registry_Offset($zookeeper, $group),
$topic,
$socketBufferSize
);
$messages = array();
try {
foreach ($zkconsumer as $message) {
// either process each message one by one, or collect them and process them in batches
$messages[] = $message;
if ($zkconsumer->getReadBytes() >= $maxBatchSize) {
break;
}
}
} catch (Kafka_Exception_OffsetOutOfRange $exception) {
// if we haven't received any messages, resync the offsets for the next time, then bomb out
if ($zkconsumer->getReadBytes() == 0) {
$zkconsumer->resyncOffsets();
die($exception->getMessage());
}
// if we did receive some messages before the exception, carry on.
} catch (Kafka_Exception_Socket_Connection $exception) {
// deal with it below
} catch (Kafka_Exception $exception) {
// deal with it below
}
if (null !== $exception) {
// if we haven't received any messages, bomb out
if ($zkconsumer->getReadBytes() == 0) {
die($exception->getMessage());
}
// otherwise log the error, commit the offsets for the messages read so far and return the data
}
// process the data in batches, wait for ACK
$success = doSomethingWithTheMessages($messages);
// Once the data is processed successfully, commit the byte offsets.
if ($success) {
$zkconsumer->commitOffsets();
}
// get an approximate figure on the size of the queue
try {
echo "\nRemaining bytes in queue: " . $consumer->getRemainingSize();
} catch (Kafka_Exception_Socket_Connection $exception) {
die($exception->getMessage());
} catch (Kafka_Exception $exception) {
die($exception->getMessage());
}
kafka-php的更多相关文章
- Spark踩坑记——Spark Streaming+Kafka
[TOC] 前言 在WeTest舆情项目中,需要对每天千万级的游戏评论信息进行词频统计,在生产者一端,我们将数据按照每天的拉取时间存入了Kafka当中,而在消费者一端,我们利用了spark strea ...
- 消息队列 Kafka 的基本知识及 .NET Core 客户端
前言 最新项目中要用到消息队列来做消息的传输,之所以选着 Kafka 是因为要配合其他 java 项目中,所以就对 Kafka 了解了一下,也算是做个笔记吧. 本篇不谈论 Kafka 和其他的一些消息 ...
- kafka学习笔记:知识点整理
一.为什么需要消息系统 1.解耦: 允许你独立的扩展或修改两边的处理过程,只要确保它们遵守同样的接口约束. 2.冗余: 消息队列把数据进行持久化直到它们已经被完全处理,通过这一方式规避了数据丢失风险. ...
- .net windows Kafka 安装与使用入门(入门笔记)
完整解决方案请参考: Setting Up and Running Apache Kafka on Windows OS 在环境搭建过程中遇到两个问题,在这里先列出来,以方便查询: 1. \Jav ...
- kafka配置与使用实例
kafka作为消息队列,在与netty.多线程配合使用时,可以达到高效的消息队列
- kafka源码分析之一server启动分析
0. 关键概念 关键概念 Concepts Function Topic 用于划分Message的逻辑概念,一个Topic可以分布在多个Broker上. Partition 是Kafka中横向扩展和一 ...
- Kafka副本管理—— 为何去掉replica.lag.max.messages参数
今天查看Kafka 0.10.0的官方文档,发现了这样一句话:Configuration parameter replica.lag.max.messages was removed. Partiti ...
- Kafka:主要参数详解(转)
原文地址:http://kafka.apache.org/documentation.html ############################# System ############### ...
- kafka
2016-11-13 20:48:43 简单说明什么是kafka? Apache kafka是消息中间件的一种,我发现很多人不知道消息中间件是什么,在开始学习之前,我这边就先简单的解释一下什么是消息 ...
- Spark Streaming+Kafka
Spark Streaming+Kafka 前言 在WeTest舆情项目中,需要对每天千万级的游戏评论信息进行词频统计,在生产者一端,我们将数据按照每天的拉取时间存入了Kafka当中,而在消费者一端, ...
随机推荐
- [Flex] 组件Tree系列 —— 运用LabelFunction hasChildren getChildren设置Tree包含节点个数
mxml: <?xml version="1.0" encoding="utf-8"?> <!--功能描述:运用LabelFunction h ...
- linux系统下运行java项目的脚本编写
本文主要讲linux系统下运行jar包,至于如何打包jar包,放到linux系统下可以参考其他的博客. 在linux系统下运行jar包的命令如下: 1.java -jar xxxxx.jar // ...
- iOS学习笔记(1)--认识Xcode6.1的Interface Builder和常用快捷键
Interface Builder基本界面 红色区域为工具栏(Tool Bar) 蓝色区域为导航区(Navigator Area) 绿色区域为编辑区(Editor Area) 黑色区域是调试区(Deb ...
- Schema Workbench 启动慢
原始是JDBC连接设定的时候需要在参数中增加下列选项 FILTER_SCHEMA_LIST 官方的解释是 就是去搜寻连接数据库的所有的表结构,表越大越慢. 也要把这选项去除,保存数据库链接,并重新登录 ...
- pydicom读取dicom文件报错
之前采用pydicom读取dicom文件一切都很正常,不过最近读取一批数据的时候,会报错 读取代码 file = pydicom.read_file(filepath) data = file.pix ...
- try语句块和异常处理
在C++中,异常处理包括: · throw表达式(throw expression) 异常检测部分使用throw表达式来表示它遇到了无法处理的问题.throw表达式抛出一个异常并把控制权转移到能处理该 ...
- AVL树插入(Python实现)
建立AVL树 class AVLNode(object): def __init__(self,data): self.data = data self.lchild = None self.rchi ...
- 三种实现日志过滤器的方式 (过滤器 (Filter)、拦截器(Interceptors)和切面(Aspect))
1.建立RequestWrapper类 import com.g2.order.server.utils.HttpHelper; import java.io.BufferedReader; impo ...
- shell map使用
# 定义初始化map declare -A map=([") # 输出所有key echo ${map[@]} # 输出key对应的值 "]} # 遍历map for key in ...
- 2.使用ngx_http_auth_basic_module模块为不带认证的资源添加授权
1.首先需要生成用户名和密码 使用openssl来生成,生成命令(openssl在安装nginx的时候已经安装) echo "kibana:$(openssl passwd -crypt y ...