jrbecart / influxdb-php
PHP 的 InfluxDB 客户端库
Requires
- php: ^5.5 || ^7.0 || ^8.0
- guzzlehttp/guzzle: ^6.0|^7.0
Requires (Dev)
- dms/phpunit-arraysubset-asserts: ^0.2.1
- phpunit/phpunit: ^9.5
Suggests
- ext-curl: Curl extension, needed for Curl driver
- stefanotorresi/influxdb-php-async: An asyncronous client for InfluxDB, implemented via ReactPHP.
This package is not auto-updated.
Last update: 2024-09-20 05:06:05 UTC
README
PHP 的 InfluxDB 客户端库
注意:此库适用于 InfluxDB 1.x。要连接到 InfluxDB 2.x 实例,请使用 influxdb-client-php 客户端。
概述
一个易于使用的库,用于用 PHP 操作 InfluxDB。由 @thecodeassassin,@gianarb 维护。
创建 influxdb-php 库是为了将 Python influxdb 客户端移植到 PHP。这样,就可以在不同的编程语言之间有一个共同的抽象库。
安装
可以使用 composer 进行安装
$ composer require jrbecart/influxdb-php
针对 PHP 5.3 和 PHP 5.4 用户的注意
如果您使用的是 PHP 5.3 或 PHP 5.4,0.1.x 版本仍然受到支持(修复错误和新版本修复)。0.1.x 分支将在 PHP 5.3 和 PHP 5.4 上运行,但不包含 1.0.0 版本具有的所有功能,例如 UDP 支持。
入门
初始化新的客户端对象
$client = new InfluxDB\Client($host, $port);
这将创建一个新的客户端对象,您可以使用它来读取和写入 InfluxDB 中的点。
还可以从 DSN(数据源名称)创建客户端
// directly get the database object $database = InfluxDB\Client::fromDSN(sprintf('influxdb://user:pass@%s:%s/%s', $host, $port, $dbname)); // get the client to retrieve other databases $client = $database->getClient();
重要:当使用 DSN 时,不要忘记对密码(以及用户名)进行 urlencode() 编码,特别是如果它包含非字母数字字符。否则可能会引发异常。
读取数据
要从 InfluxDB 获取记录,可以直接对数据库进行查询
// fetch the database $database = $client->selectDB('influx_test_db'); // executing a query will yield a resultset object $result = $database->query('select * from test_metric LIMIT 5'); // get the points from the resultset yields an array $points = $result->getPoints();
还可以使用 QueryBuilder 对象。这是一个简化查询构建过程的类。
// retrieve points with the query builder $result = $database->getQueryBuilder() ->select('cpucount') ->from('test_metric') ->limit(2) ->offset(2) ->getResultSet() ->getPoints(); // get the query from the QueryBuilder $query = $database->getQueryBuilder() ->select('cpucount') ->from('test_metric') ->where(["region = 'us-west'"]) ->getQuery();
确保在字符串上进行 where 查询时输入单引号;否则,InfluxDB 将返回空结果。
您可以从客户端获取最后执行的查询
// use the getLastQuery() method $lastQuery = $client->getLastQuery(); // or access the static variable directly: $lastQuery = Client::lastQuery;
使用超时读取数据
在生产环境中,如果您正在查询 InfluxDB 以生成对 Web 或 API 请求的响应,您可能希望为 InfluxDB 调用设置特定的超时,而不是默认无限期运行。
// Fetch the database using a 5 second time out $database = InfluxDB\Client::fromDSN(sprintf('influxdb://user:pass@%s:%s/%s', $host, $port, $dbname), 5);
写入数据
通过向数据库的 writePoints 方法提供一个点的数组来写入数据
// create an array of points $points = array( new Point( 'test_metric', // name of the measurement 0.64, // the measurement value ['host' => 'server01', 'region' => 'us-west'], // optional tags ['cpucount' => 10], // optional additional fields 1435255849 // Time precision has to be set to seconds! ), new Point( 'test_metric', // name of the measurement 0.84, // the measurement value ['host' => 'server01', 'region' => 'us-west'], // optional tags ['cpucount' => 10], // optional additional fields 1435255849 // Time precision has to be set to seconds! ) ); // we are writing unix timestamps, which have a second precision $result = $database->writePoints($points, Database::PRECISION_SECONDS);
在将测量写入 InfluxDB 时,可以添加多个 字段。Point 类允许用户轻松地将数据批量写入 influxDB。
测量名称和值是必需的。额外的字段、标签和时间戳是可选的。InfluxDB 使用当前时间作为默认时间戳。
您还可以在不指定值的情况下将多个字段写入测量
$points = [ new Point( 'instance', // the name of the measurement null, // measurement value ['host' => 'server01', 'region' => 'us-west'], // measurement tags ['cpucount' => 10, 'free' => 1], // measurement fields exec('date +%s%N') // timestamp in nanoseconds on Linux ONLY ), new Point( 'instance', // the name of the measurement null, // measurement value ['host' => 'server01', 'region' => 'us-west'], // measurement tags ['cpucount' => 10, 'free' => 2], // measurement fields exec('date +%s%N') // timestamp in nanoseconds on Linux ONLY ) ];
使用 udp 写入数据
首先,将 InfluxDB 主机设置为支持传入的 UDP 套接字
[udp] enabled = true bind-address = ":4444" database = "test_db"
然后,在客户端中配置 UDP 驱动程序
// set the UDP driver in the client $client->setDriver(new \InfluxDB\Driver\UDP($client->getHost(), 4444)); $points = [ new Point( 'test_metric', 0.84, ['host' => 'server01', 'region' => 'us-west'], ['cpucount' => 10], exec('date +%s%N') // this will produce a nanosecond timestamp on Linux ONLY ) ]; // now just write your points like you normally would $result = $database->writePoints($points);
或者简单地使用 DSN(数据源名称)通过 UDP 发送指标
// get a database object using a DSN (Data Source Name) $database = \InfluxDB\Client::fromDSN('udp+influxdb://username:pass@localhost:4444/test123'); // write your points $result = $database->writePoints($points);
注意: 使用 UDP 时,将忽略精度。您应该始终在写入 InfluxDB 数据时使用纳秒精度。
时间戳精度
在向 Point 对象添加时间戳时提供正确的精度很重要。这是因为如果您指定了以秒为单位的时间戳,并且默认(纳秒)精度已设置;则输入的时间戳将无效。
// Points will require a nanosecond precision (this is default as per influxdb standard) $newPoints = $database->writePoints($points); // Points will require second precision $newPoints = $database->writePoints($points, Database::PRECISION_SECONDS); // Points will require microsecond precision $newPoints = $database->writePoints($points, Database::PRECISION_MICROSECONDS);
请注意,exec('date + %s%N') 在 MacOS 下不起作用;您可以使用 PHP 的 microtime 获取微秒精度的时间戳,如下所示
list($usec, $sec) = explode(' ', microtime()); $timestamp = sprintf('%d%06d', $sec, $usec*1000000);
创建数据库
在创建数据库时,会添加一个默认的保留策略。这个保留策略没有持续时间,所以数据将与内存一起刷新。
这个库使得在创建数据库时提供保留策略变得简单。
// create the client $client = new \InfluxDB\Client($host, $port, '', ''); // select the database $database = $client->selectDB('influx_test_db'); // create the database with a retention policy $result = $database->create(new RetentionPolicy('test', '5d', 1, true)); // check if a database exists then create it if it doesn't $database = $client->selectDB('test_db'); if (!$database->exists()) { $database->create(new RetentionPolicy('test', '1d', 2, true)); }
您还可以修改保留策略。
$database->alterRetentionPolicy(new RetentionPolicy('test', '2d', 5, true));
并列出它们。
$result = $database->listRetentionPolicies();
您可以为数据库添加更多保留策略。
$result = $database->createRetentionPolicy(new RetentionPolicy('test2', '30d', 1, true));
客户端函数
一些函数对于数据库来说太通用。因此,这些函数在客户端可用。
// list users $result = $client->listUsers(); // list databases $result = $client->listDatabases();
管理功能
您可以使用客户端的 $client->admin 功能通过 API 管理InfluxDB。
// add a new user without privileges $client->admin->createUser('testuser123', 'testpassword'); // add a new user with ALL cluster-wide privileges $client->admin->createUser('admin_user', 'password', \InfluxDB\Client\Admin::PRIVILEGE_ALL); // drop user testuser123 $client->admin->dropUser('testuser123');
列出所有用户
// show a list of all users $results = $client->admin->showUsers(); // show users returns a ResultSet object $users = $results->getPoints();
授权和撤销权限
授权可以在数据库级别和集群范围内进行。要授权用户对数据库的特定权限,请提供数据库对象或数据库名称。
// grant permissions using a database object $database = $client->selectDB('test_db'); $client->admin->grant(\InfluxDB\Client\Admin::PRIVILEGE_READ, 'testuser123', $database); // give user testuser123 read privileges on database test_db $client->admin->grant(\InfluxDB\Client\Admin::PRIVILEGE_READ, 'testuser123', 'test_db'); // revoke user testuser123's read privileges on database test_db $client->admin->revoke(\InfluxDB\Client\Admin::PRIVILEGE_READ, 'testuser123', 'test_db'); // grant a user cluster-wide privileges $client->admin->grant(\InfluxDB\Client\Admin::PRIVILEGE_READ, 'testuser123'); // Revoke an admin's cluster-wide privileges $client->admin->revoke(\InfluxDB\Client\Admin::PRIVILEGE_ALL, 'admin_user');
待办事项
- 更多单元测试
- 增加文档(维基百科?)
- 向查询构建器添加更多功能
- 向RetentionPolicy添加验证
变更日志
1.15.0
- 添加了cURL驱动程序支持 #122(感谢 @aldas)
- 改进了查询错误信息 #129(感谢 @andreasanta)
1.14.8
- 合并了 #122
1.14.7
- 添加了QueryBuilder中的偏移量(感谢 @lifekent 和 @BentCoder)
1.14.6
- 依赖项更新 (#97),由 @aldas
- 添加超时信息。(#103),由 @NickBusey
- 添加指定guzzle的connect_timeout的能力(#105),由 @brycefranzen
1.14.5
- 更新关键概念链接以指向正确的位置。
- 将昂贵的array_merge调用替换为foreach + array运算符
- 添加verifySSL的获取方法
- 支持Symfony 4
1.14.3
- 废弃数据库创建中的IF NOT EXISTS子句
1.14.2
- 修复了在调用InfluxDB\Client::fromDSN时未提供用户名或密码时的警告
- 修复了Guzzle客户端超时为浮点数的问题
- 修复了注释
- 删除未使用的属性
- 修复了拼写错误
- 修复了具有Boolean/Null值的标签触发解析错误
1.4.1
- 修复了问题:根据行协议转义字段值。
1.4.0
- 更新Influx数据库,支持直接写入有效载荷,感谢 @virgofx
1.3.1
- 添加了将数据写入特定保留策略的能力,感谢 @virgofx !
1.3.0
- 在查询中添加了对dbname的引号
- 向查询构建器添加了orderBy
- 修复了错误的orderby测试
- Travis容器基础设施和php 7
1.2.2
- 修复了listUsers()方法的问题
- 添加了更多单元测试
- 向\InfluxDB\ResultSet添加了getColumns方法
1.2.0
- 添加了对32位系统的支持
- 为Point字段添加了设置器/获取器
1.1.3
- 添加了对symfony3的支持
1.1.2
- 修复了写入数据时的认证问题
1.1.1
- 添加了对0.9.4的支持
- 向database->create()添加了if not exists支持
- 添加了getLastQuery方法
1.1.0
- 添加了对0.9.3 rc2的支持
- 更改了处理值的数据类型的方式
- 更改了保留策略列表以反映0.9.3中的更改
1.0.1
- 向guzzle驱动程序添加了认证支持
- 添加了管理功能
1.0.0
- -重大更改- 废弃了对PHP 5.3和PHP 5.4的支持
- 允许使用自定义驱动程序
- UDP支持
0.1.2
- 向Database类添加了exists方法
- 向数据库类添加了时间精度
0.1.1
- 将存储库合并到influxdb/influxdb-php中
- 为createRetentionPolicy添加了单元测试
- -重大更改- 将 $client->db 更改为 $client->selectDB