Net6 操作時序數據庫influxdb,數據插入查詢/增刪存儲桶

十年河東,十年河西,莫騎少年窮

學無止境,精益求精

官方文檔: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纔可以完成

 

 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

#@陳臥龍的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章