InfluxDB简介与php用法

InfluxDB(时序数据库),常用的一种使用场景:监控数据统计。每毫秒记录一下电脑内存的使用情况,然后就可以根据统计的数据,利用图形化界面(InfluxDB V1一般配合Grafana)制作内存使用情况的折线图;
这里输入引用文本可以理解为按时间记录一些数据(常用的监控数据、埋点统计数据等),然后制作图表做统计。

一、什么是influxDB

InfluxDB是一个由InfluxData开发的开源时序型数据。它由Go写成,着力于高性能地查询与存储时序型数据。InfluxDB被广泛应用于存储系统的监控数据,IoT行业的实时数据等场景。在操作频繁且易并发的情况下使用它来存储很nice.例如蚂蚁森林收取能量业务。

二、对常见关系型数据库(MySQL)的基础概念对比

概念 MySQL InfluxDB
数据库(同) database database
表(不同) table measurement
列(不同) column tag(带索引的,非必须)、field(不带索引)、timestemp(唯一主键)
  • tag set:不同的每组tag key和tag value的集合;
  • field set:每组field key和field value的集合;
  • retention policy:数据存储策略(默认策略为autogen)InfluxDB没有删除数据操作,规定数据的保留时间达到清除数据的目的;
  • series:共同retention policy,measurement和tag set的集合;

示例数据如下: 其中census是measurement,butterflies和honeybees是field key,location和scientist是tag key

name: census
————————————
time                 butterflies     honeybees     location     scientist
2015-08-18T00:00:00Z      12             23           1         langstroth
2015-08-18T00:00:00Z      1              30           1         perpetua
2015-08-18T00:06:00Z      11             28           1         langstroth
2015-08-18T00:06:00Z      11             28           2         langstroth

示例中有三个tag set

三、注意点

  • tag 只能为字符串类型
  • field 类型无限制
  • 不支持join
  • 支持连续查询操作(汇总统计数据):CONTINUOUS QUERY
  • 配合Telegraf服务(Telegraf可以监控系统CPU、内存、网络等数据)
  • 配合Grafana服务(数据展现的图像界面,将influxdb中的数据可视化)

四、常用influxQL

-- 查看所有的数据库
show databases;
-- 使用特定的数据库
use database_name;
-- 查看所有的measurement
show measurements;
-- 查询10条数据
select * from measurement_name limit 10;
-- 数据中的时间字段默认显示的是一个纳秒时间戳,改成可读格式
precision rfc3339; -- 之后再查询,时间就是rfc3339标准格式
-- 或可以在连接数据库的时候,直接带该参数
influx -precision rfc3339
-- 查看一个measurement中所有的tag key 
show tag keys
-- 查看一个measurement中所有的field key 
show field keys
-- 查看一个measurement中所有的保存策略(可以有多个,一个标识为default)
show retention policies;
--删除数据库
drop database "db_name";
--删除数据表
drop measurement "measurement_name"

五、安装

一、InfluxDB的windows(64-bit)

1、项目中直接安装依赖
composer require influxdb/influxdb-php

下载地址为:dl.influxdata.com/influxdb/release...

2、修改influxdb.conf文件,修改meta, wal 以及 data 路径

创建三个对应文件夹。
解压完成之后分别双击influxd.exe、influx.exe 进入命令行。

当然你也可以去官方下载 选择适合自己的包
InfluxDB、Telegraf、Chronograf、Kapacitor可到下方官网下载各平台版本
下载官网:portal.influxdata.com/downloads/

二、虚拟机安装(执行命令,完成安装)

1、通过ubuntu 安装influxdb
sudo apt install influxdb
sudo apt install influxdb-client
2、查看influxdb状态,q退出。设置开机启动
//查看状态
sudo service influxdb status
//设置开机自启
sudo service influxdb start
3、启动
influxd
4、进入
influx

六、最后附上PHP 中书写示例

封装的插入方法
public static function insert(string $table,
                                  array $tags = [],
                                  array $fields = [],
                                  $value = null,
                                  $timestamp = null)
    {
        $point = new Point($table, $value, $tags, $fields, $timestamp);
        dispatch(function () use ($point) {
            InfluxDB::writePayload((string)$point);
        });
    }
使用方式: 当然前提是你得先use
InfluxDB::insert(InfluxDBTableConstants::FT, compact('user_id', 'behavior'), compact('amount', 'balance'));
//获取信息方法
public static function getPoints(string $table, array $where = [], string $order = 'time desc', int $limit = 20): array
    {
        $query_where = [];
        foreach ($where as $field => $item) {
            if (is_numeric($field)) {
                if (is_string($item) || is_numeric($item)) {
                    $query_where[] = $item;
                } else if (is_array($item)) {
                    if (count($item) === 2) {
                        $query_where[] = "{$item[0]} = '{$item[1]}'";
                    } else if (count($item) === 3) {
                        $query_where[] = "{$item[0]} {$item[1]} '{$item[2]}'";
                    } else {
                        throw new \InvalidArgumentException('where');
                    }
                } else {
                    throw new \InvalidArgumentException('where');
                }
            } else if (is_string($field)) {
                $str_where = "$field";
                if (is_string($item) || is_numeric($item)) {
                    $str_where .= " = '$item'";
                } else if (is_array($item) && count($item) === 2) {
                    $str_where .= " {$item[0]} '{$item[1]}'";
                } else {
                    throw new \InvalidArgumentException('where');
                }
                $query_where[] = $str_where;
            } else {
                throw new \InvalidArgumentException('where');
            }
        }
        $res = InfluxDB::getBuilder()->from($table)
            ->where($query_where)
            ->orderBy($order, '')
            ->limit($limit)
            ->getResultSet()
            ->getPoints();
        return $res;
    }
    public static function getData(string $table_name, array $where = []): array
    {
        $ret = [];
        $list = InfluxDB::getPoints($table_name, $where);
        if ($list) {
            $ret[] = collect($list)->map(function ($item) {
                $time = $item['time'];
                $time = explode('.', $time)[0] . '+00:00';
                $item['time'] = Carbon::parse($time)
                    ->setTimezone(config('app.timezone'))
                    ->format('Y-m-d H:i:s');
                return $item;
            })->toArray();
            $ret[] = [
                'last_time' => $list[count($list) - 1]['time']
            ];
        } else {
            $ret = [[], []];
        }
        return $ret;
    }
//以及使用方法
$wt = InfluxDB::getData(InfluxDBTableConstants::WT,$where);
本作品采用《CC 协议》,转载必须注明作者和本文链接
满腹经纶,才能江山如画。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!