Net6 操作时序数据库influxdb,数据插入查询/增删存储桶

时间:2022-11-26 23:01:51

十年河东,十年河西,莫骑少年穷

学无止境,精益求精

官方文档:​​https://docs.influxdata.com/influxdb/v2.4/api/​

1、项目详情

<Project Sdk="Microsoft.NET.Sdk"> 
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="InfluxDB.Client" Version="4.7.0" />
<PackageReference Include="InfluxDB.Client.Linq" Version="4.7.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\swapModels\swapModels.csproj" />
</ItemGroup>
</Project>

 引入:InfluxDB.Client、InfluxDB.Client.Linq

建立如下实体,方便查询、写入

/// <summary>
/// 类似于关系数据库的表名
/// </summary>
[Measurement("pack")]
internal class packdto
{
/// <summary>
/// 标签
/// </summary>
[Column("car", IsTag = true)]
public string car { get; set; }
/// <summary>
/// 普通字段
/// </summary>
[Column("money")]
public double money { get; set; }
/// <summary>
/// 普通字段
/// </summary>
[Column("temp")]
public int temp { get; set; }
/// <summary>
/// 普通字段--中文值
/// </summary>
[Column("tempCn")]
public string tempCn { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Column(IsTimestamp = true)]
public DateTime Timestamp { get; set; }
}

View Code

2、写入数据

数据点格式插入

static void Insert()
{
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{

var point = PointData
.Measurement("pack")
.Tag("car", "苏E.P6M88")
.Field("money", 28.43)
.Field("temp", 23)
.Field("tempCn", "开")
.Timestamp(DateTime.UtcNow, WritePrecision.Ns);

var point2 = PointData
.Measurement("pack")
.Tag("car", "苏E.P6M66")
.Field("money", 28.43)
.Field("temp", 28)
.Field("tempCn", "关")
.Timestamp(DateTime.UtcNow, WritePrecision.Ns);

var point3 = PointData
.Measurement("pack")
.Tag("car", "苏U.P6M22")
.Field("money", 28.43)
.Field("tempCn", "未知")
.Field("temp", 32)
.Timestamp(DateTime.UtcNow, WritePrecision.Ns);

var point4 = PointData
.Measurement("pack")
.Tag("car", "苏U.P6M55")
.Field("money", 100)
.Field("tempCn", "未知")
.Field("temp", 42)
.Timestamp(DateTime.UtcNow, WritePrecision.Ns);

using (var writeApi = client.GetWriteApi())
{
writeApi.WritePoint(point, bucket, org);
writeApi.WritePoint(point2, bucket, org);
writeApi.WritePoint(point3, bucket, org);
writeApi.WritePoint(point4, bucket, org);
}
}

}

View Code

实体格式插入

static void Insert()
{
var dto = new packdto { car = "苏U.ddddd", money = 123.488, temp=122.0, Timestamp = DateTime.UtcNow };
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{
using (var writeApi = client.GetWriteApi())
{
writeApi.WriteMeasurement<packdto>(dto,WritePrecision.Ns,bucket,org);
}
}
}

View Code

3、查询数据

3.1、查询所有

固定参数:

const string token = "vOhsFHRB2q9Ax4v3dZS67pJjJqtJnI-cAFZoUsWb-ZQITPXJbpdyvtwXwK6zRWSVOUcNJV4xEywtUSN_lC-ebg==";
const string bucket = "packing";
const string org = "wuan";

查询所有

static List<packdto> QueryAll()
{
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{
var query = from s in InfluxDBQueryable<packdto>.Queryable(bucket, org, client.GetQueryApiSync())
orderby s.Timestamp
select s;
var datas = query.ToList();
return datas;
}
}

View Code

3.2、条件过滤

条件过滤时,需要将时间转为Utc时间,也就是减去8个小时

static List<packdto> QueryBy(string car,double money,DateTime? stime,DateTime? etime)
{
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{
var query = from s in InfluxDBQueryable<packdto>.Queryable(bucket, org, client.GetQueryApiSync())
select s;
if (!string.IsNullOrEmpty(car))
{
query = query.Where(A => A.car == car);
}
if (money>0)
{
query = query.Where(A => A.money>money);
}
if (stime.HasValue)
{
var tim = stime.Value;
query = query.Where(A => A.Timestamp >= new DateTime(tim.Year, tim.Month, tim.Day, tim.Hour-8, tim.Minute, tim.Second, DateTimeKind.Utc));
}
if (etime.HasValue)
{
var tim = etime.Value;
query = query.Where(A => A.Timestamp < new DateTime(tim.Year, tim.Month, tim.Day, tim.Hour-8, tim.Minute, tim.Second, DateTimeKind.Utc));
}
var datas = query.ToList();
return datas;
}
}

View Code

调佣条件过滤函数

展示时间时,需要将时间小时部分加8,展示为北京时间

static void Main(string[] args)
{
var data = QueryBy("苏E.P6M66",10 ,Convert.ToDateTime("2022-11-22 10:50:00"),DateTime.Now);
foreach(var item in data)
{
Console.WriteLine($"carNo:{item.car},money:{item.money},temp:{item.temp},tempCn:{item.tempCn},time:{item.Timestamp.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss")}");
}
Console.ReadKey();
}

View Code

4、创建/删除存储桶

存储桶相当于关系型数据库中的数据库,因此,此操作慎重执行

4.1、创建新的存储桶,并制定数据有效期一小时

static async Task CreateNewBucket(CancellationToken cancellation=default)
{
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{
var orgId = client.GetOrganizationsApi().FindOrganizationsAsync(org: org).Result.First().Id;
var retention = new BucketRetentionRules(BucketRetentionRules.TypeEnum.Expire, 3600);
var newBucket = client.GetBucketsApi().CreateBucketAsync("iot_bucket2", retention, orgId).Result;
}
}

View Code

注意上述代码的Token,需要使用最大权限的TOKEN才可以完成

Net6 操作时序数据库influxdb,数据插入查询/增删存储桶

 

 4.2、删除存储桶

static async Task deleteBucket(CancellationToken cancellation=default)
{
using (var client = InfluxDBClientFactory.Create("http://localhost:8086", token))
{
var api = client.GetBucketsApi();
var bkr =await api.FindBucketByNameAsync("iot_bucket2", cancellation);
if (bkr != null)
{
await api.DeleteBucketAsync(bkr);
}
//var newBucket = await client.GetBucketsApi().DeleteBucketAsync("iot_bucket2");
}
}

View Code

删除存储桶和创建存储桶一样,都必须提供最大权限的Token

 5、总结

无论是C# 还是java,PHP等编程语言都通过各自的方式集成了influxdb的操作Api

以C#为例,简单贴出如下几个

using (var client = InfluxDBClientFactory.Create(url, token))
{
var api = client.GetDeleteApi();
var api2 = client.GetBucketsApi();
var api3 = client.GetChecksApi();
var api4 = client.GetWriteApi();
var api5 = client.GetLabelsApi();
}

需要说明的是,这里的Token需要根据不同API提供不同权限的TOKEN

#@陈卧龙的博客