C# 读写亿级InfluxDB数据库

By qq84628151 没有评论

首先浏览器进入8086端口拿到Token

下面代码是一次性写入10万条数据,我电脑运行花了1.7815181(秒),注意的是时间戳不能相同,否则会替换原来的数据

const string token = "Mr90dEnu9rrkH47afvAcoQWqIXjWxOiox93k1JdNZZPy6EB5RtJ7pS5-YZoB6aW5-AgwQ-_NIkWwAF5eYCdbLA==";
const string bucket = "Test_Data1";
const string org = "Group1";
Random random = new Random();
//开始计算时间
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//通过工厂方法创建一个实例
var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", token);
//存储10万数据的列表
List<PointData> writeList = new List<PointData>();
var dt = DateTime.UtcNow;

for (int i = 0; i < 100000; ++i)
{
    writeList.Add(PointData.Measurement("temperature")
        .Tag("location", "test6")
        .Field("value", random.NextDouble() * 30)
        .Timestamp(dt.AddMilliseconds(i), WritePrecision.Ns));
}

using (var writeApi = influxDBClient.GetWriteApi())
{
    writeApi.WritePoints(bucket, org, writeList.ToArray());
}
//停止计算时间
stopWatch.Stop();
//显示运行总秒数
Console.WriteLine("RunTime " + stopWatch.Elapsed.TotalSeconds);

下面代码是读取最近1小时的数据,有10万条数据,并且做了一些过滤,电脑运行程序花了1.4252552(秒)

Stopwatch stopWatch2 = new Stopwatch();
stopWatch2.Start();
//根据最近1小时数据,并添加一些筛选条件过滤
var tables = influxDBClient.GetQueryApi().QueryAsync($"from(bucket: \"{ bucket}\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"temperature\" and r.location == \"test6\")", org);
//获取结果
var result = tables.Result;
stopWatch2.Stop();
TimeSpan ts2 = stopWatch2.Elapsed;
Console.WriteLine("RunTime " + ts2.TotalSeconds);