秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
秋枫阁,秋枫阁-科技馆,Blog,博客,个人博客,Maple,Zoe,Maple与Zoe
Influxdb在Laravel中的基本应用
- 时间:2019-01-05 12:22:26
- 3471人已阅读
简介分享一次在Laravel中使用Influxdb(时序数据库)记录采集过程中的数据日志,本文介绍Influxdb在Laravel中的基本应用
InfluxDB是一个开源的时序数据库,使用GO语言开发,特别适合用于处理和分析资源监控数据这种时序相关数据。而InfluxDB自带的各种特殊函数如求标准差,随机取样数据,统计数据变化比等,使数据统计和实时分析变得十分方便。
在本次项目中,需要将采集的数据实时记录存档,用以对比监控接口数据变化线性规律,故此我选用了InfluxDB,下面记录一下使用过程中所得。
Mac OS安装InfluxDB:
brew update
brew install influxdb
Docker安装InfluxDB:
docker pull influxdb
在实际安装过程中,只需要选好对应的版本,然后按照命令执行就可以了。
启动
# 后台启动
brew services start influxdb
# 非后台启动
influxd -config /usr/local/etc/influxdb.conf
# 如果直接下载的二进制包,则通过如下方式启动
进入InfluxDB目录下的usr/bin文件夹
./influxd
在Laravel中的使用:
安装Influxdb-php:
composer require influxdb/influxdb-php
创建客户端:
$client = new InfluxDB\Client($host, $port);
从 DNS 创建客户端:
$database = InfluxDB\Client::fromDSN(sprintf('influxdb://user:pass@%s:%s/%s', $host, $port, $dbname));
获取客户端来检索其他数据库:
$client = $database->getClient();
数据库执行
选择数据库:
$database = $client->selectDB('influx_test_db');
执行sql:
$result = $database->query('select * from test_metric LIMIT 5');
获取结果集数组:
$points = $result->getPoints();
通过 QueryBuilder 对象查询:
// 用查询生成器生成检索
$result = $database->getQueryBuilder()
->select('cpucount')
->from('test_metric')
->limit(2)
->getResultSet()
->getPoints();
从 QueryBuilder 中获取查询:
$query = $database->getQueryBuilder();
->select('cpucount')
->from('test_metric')
->where(["region = 'us-west'"])
->getQuery();
获取上次的查询:
// 使用 getLastQuery() 方法
$lastQuery = $client->getLastQuery();
// 直接访问静态变量
$lastQuery = Client::lastQuery;
写数据
// 创建一个数组
$points = array( new Point( 'test_metric', // 测试名称 0.64, // 测试值 ['host' => 'server01', 'region' => 'us-west'], // 可选标记 ['cpucount' => 10], // 可选附加字段 1435255849 // 时间精度必须设置为秒 ), new Point( 'test_metric', 0.84, ['host' => 'server01', 'region' => 'us-west'], ['cpucount' => 10], 1435255849 ) ); // 正在写unix时间戳,它有第二个精度
$result = $database->writePoints($points, Database::PRECISION_SECONDS);
时间戳精度
// Points 需要纳秒精度(根据influxdb标准,这是默认值)
$newPoints = $database->writePoints($points);
// Points 需要第二个精度
$newPoints = $database->writePoints($points, Database::PRECISION_SECONDS);
// Points 需要微秒精度
$newPoints = $database->writePoints($points, Database::PRECISION_MICROSECONDS);
创建数据库
// 创建客户端
$client = new \InfluxDB\Client($host, $port, '', '');
// 选择数据库
$database = $client->selectDB('influx_test_db');
// 使用保留策略创建数据库
$result = $database->create(new RetentionPolicy('test', '5d', 1, true));
// 检查数据库是否存在,如果不存在,则创建它
$database = $client->selectDB('test_db');
if (!$database->exists()) {
$database->create(new RetentionPolicy('test', '1d', 2, true));
}
上一篇:分享一个简单实用的Curl类
下一篇:一周