C# influxDB 帮助类
时间: 2024-11-07 21:11:53 浏览: 13
InfluxDB 是一个分布式、时间序列数据库,常用于收集和分析实时数据。在 C# 中,你可以通过 InfluxDB .NET 客户端库 (InfluxDB.Client) 来与 InfluxDB 服务交互。以下是一个简单的帮助类示例,该类封装了常见的操作如插入数据点、查询数据等:
```csharp
using InfluxDB.Net;
using InfluxDB.Net.Common;
using System.Threading.Tasks;
public class InfluxDbHelper
{
private readonly IInfluxDatabase _influxDatabase;
private const string BucketName = "your_bucket_name";
private const string DatabaseUrl = "http://localhost:8086"; // 根据实际情况替换
private const string Username = "your_username";
private const string Password = "your_password";
public InfluxDbHelper(string databaseName)
{
var options = new InfluxOptions.Builder()
.Uri(new Uri(DatabaseUrl))
.Username(Username)
.Password(Password)
.Build();
_influxDatabase = new InfluxClient(options).GetDatabase(databaseName);
}
// 插入数据点
public async Task InsertMeasurementAsync(string measurementName, Dictionary<string, object> fields, DateTime timestamp)
{
using var batch = new WritePointBatch(BucketName);
batch.AddPoint(measurementName, fields, new PointField("time", timestamp));
await _influxDatabase.WriteAsync(batch);
}
// 查询数据
public async Task<IEnumerable<Measurment>> GetMeasurementsAsync(string query)
{
return await _influxDatabase.QuerySingleSeriesAsync(query);
}
}
// 使用示例
public async void Main()
{
var helper = new InfluxDbHelper("your_database");
await helper.InsertMeasurementAsync("example_measurement", new { temperature = 25 }, DateTime.UtcNow);
var results = await helper.GetMeasurementsAsync("SELECT * FROM example_measurement");
}
```
阅读全文