溫馨提示×

influxdb php有案例分享嗎

PHP
小樊
81
2024-10-17 21:22:06
欄目: 編程語言

當然有!以下是一個使用 PHP 與 InfluxDB 交互的簡單示例。這個示例展示了如何連接到 InfluxDB,寫入數(shù)據(jù),然后讀取數(shù)據(jù)。

1. 安裝 InfluxDB PHP 客戶端

首先,確保你已經(jīng)安裝了 InfluxDB,然后使用 Composer 安裝 PHP 客戶端庫:

composer require influxdb/influxdb-client

2. 編寫 PHP 代碼

創(chuàng)建一個名為 influxdb_example.php 的文件,并添加以下代碼:

<?php
require 'vendor/autoload.php';

use InfluxDB\Client\InfluxDBClient;
use InfluxDB\Client\WriteApi;
use InfluxDB\Model\Point;

// 配置 InfluxDB 連接信息
$host = 'localhost';
$port = 8086;
$user = 'root';
$password = 'root';
$database = 'mydb';

// 創(chuàng)建 InfluxDBClient 實例
$client = new InfluxDBClient([
    'url' => "http://${host}:${port}",
    'username' => $user,
    'password' => $password
]);

// 選擇要寫入的數(shù)據(jù)庫
$writeApi = $client->getWriteApi($database);

// 寫入數(shù)據(jù)
$point = Point::measurement('my_measurement')
    ->addField('value', 1)
    ->time(new \DateTime('2023-04-01T12:00:00Z'));

$writeApi->writePoint($point);
$writeApi->close();

// 讀取數(shù)據(jù)
$queryApi = $client->getQueryApi($database);
$query = 'from(bucket:"mydb") |> range(start: -1h)';
$result = $queryApi->collectRows($query);

echo "Data:\n";
foreach ($result as $row) {
    echo "Time: " . $row['_time'] . ", Value: " . $row['value'] . "\n";
}

// 關(guān)閉客戶端連接
$client->close();

3. 運行示例

確保 InfluxDB 服務(wù)正在運行,然后在命令行中運行以下命令:

php influxdb_example.php

你應(yīng)該會看到類似以下的輸出:

Data:
Time: 2023-04-01T12:00:00Z, Value: 1

這個示例展示了如何使用 PHP 與 InfluxDB 進行基本的讀寫操作。你可以根據(jù)自己的需求擴展這個示例,例如添加更多的數(shù)據(jù)點、使用不同的時間范圍等。

0