首页 > 编程语言 >InfluxDB V2.5 C# Hepler 类及使用实例

InfluxDB V2.5 C# Hepler 类及使用实例

时间:2022-12-20 16:56:08浏览次数:42  
标签:C# V2.5 InfluxDB DateTime client var using Now public

using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Linq;
using InfluxDB.Client.Writes;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Unit
{
    #region InfluxDB 读写工具类

    /// <summary>
    /// InfluxDB 读写工具类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class InfluxDBCommon<T>
    {
        static string _baseUri { get; set; }  //地址
        static string _token { get; set; }  //token
        static string _org { get; set; }  //组织
        static string _bucket { get; set; }  //桶
        static InfluxDBClientOptions _options { get; set; }  //桶

        /// <summary>
        /// 构造函数
        /// </summary>
        public InfluxDBCommon()
        {
            _baseUri = ConstModel.influxDBUri;
            _token = ConstModel.influxDBToken;
            _org = ConstModel.influxDBOrg;
            _bucket = ConstModel.influxDBBucket;
            _options = InfluxDBClientOptions.Builder
                          .CreateNew()
                          .Url(_baseUri)
                          .AuthenticateToken(_token)
                          .Org(_org)
                          .Bucket(_bucket)
                          .Build();
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="point"></param>
        public void WritePoint(PointData point)
        {
            var client = InfluxDBClientFactory.Create(_options);
            var writeApiAsync = client.GetWriteApiAsync();
            writeApiAsync.WritePointAsync(point);
        }

        /// <summary>
        /// 批量写入
        /// </summary>
        /// <param name="points"></param>
        public void WritePoints(List<PointData> points)
        {
            var client = InfluxDBClientFactory.Create(_options);
            var writeApiAsync = client.GetWriteApiAsync();
            writeApiAsync.WritePointsAsync(points);
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="measurement"></param>
        public void WriteMeasurement(T measurement)
        {
            var client = InfluxDBClientFactory.Create(_options);
            var writeApiAsync = client.GetWriteApiAsync();
            writeApiAsync.WriteMeasurementAsync(measurement);
        }

        /// <summary>
        /// 批量写入
        /// </summary>
        /// <param name="measurements"></param>
        public void WriteMeasurements(List<T> measurements)
        {
            var client = InfluxDBClientFactory.Create(_options);
            var writeApiAsync = client.GetWriteApiAsync();
            writeApiAsync.WriteMeasurementsAsync(measurements);
        }

        /// <summary>
        /// 查询返回 集合
        /// </summary>
        /// <param name="exp">exp 查询条件</param>
        /// <param name="orderByDesc">倒序排序字段,为数据类型时间类型的字段</param>
        /// <returns></returns>
        public List<T> QueryBy<TKey>(Expression<Func<T, bool>> exp, Expression<Func<T, TKey>> orderByDesc)
        {
            using (var client = InfluxDBClientFactory.Create(_options))
            {
                var query = from s in InfluxDBQueryable<T>.Queryable(_bucket, _org, client.GetQueryApiSync())
                            select s;
                return query.Where(exp).OrderByDescending(orderByDesc).ToList();
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="exp">where 表达式</param>
        /// <param name="orderByDesc">排序字段</param>
        /// <param name="skip">当前第几页</param>
        /// <param name="take">每页多少条</param>
        /// <param name="count">返回总行数</param>
        /// <returns>返回分页后结果</returns>
        public List<T> QueryBy<TKey>(Expression<Func<T, bool>> exp, Expression<Func<T, TKey>> orderByDesc, int skip, int take, out int count)
        {
            using (var client = InfluxDBClientFactory.Create(_options))
            {
                var query = from s in InfluxDBQueryable<T>.Queryable(_bucket, _org, client.GetQueryApiSync())
                            select s;
                count = query.Where(exp).Count();
                return query.Where(exp).OrderByDescending(orderByDesc).Skip(skip).Take(take).ToList();
            }
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns>返回Measurement 所有数据</returns>
        public List<T> QueryAll()
        {
            using (var client = InfluxDBClientFactory.Create(_options))
            {
                var query = from s in InfluxDBQueryable<T>.Queryable(_bucket, _org, client.GetQueryApiSync())
                            select s;
                return query.ToList();
            }
        }

    }

    #endregion

    #region 使用实例
    public class InfluxDBTest
    {
        public void Test() 
        {
            //声明
            var influx = new InfluxDBCommon<PointDataList>();

            //单个写入
            PointDataList point = new PointDataList() { PointCode = "A0005", PointValue = "1", CreateTime = DateTime.Now, CreateTimeTicks = DateTime.Now.Ticks, Timestamp = DateTime.UtcNow };
            influx.WriteMeasurement(point);

            var pointInfo = PointData
             .Measurement("PointDataList")
             .Tag("pointcode", "DB001")
             .Field("pointvalue", "2#报警信息。。。。。");
            influx.WritePoint(pointInfo);

            //批量写入
            List<PointDataList> Lsts = new List<PointDataList>();
            Lsts.Add(new PointDataList() { PointCode = "A0006", PointValue = "true", CreateTime = DateTime.Now, CreateTimeTicks = DateTime.Now.Ticks, Timestamp = DateTime.UtcNow });
            Lsts.Add(new PointDataList() { PointCode = "A0007", PointValue = "false", CreateTime = DateTime.Now, CreateTimeTicks = DateTime.Now.Ticks, Timestamp = DateTime.UtcNow });
            Lsts.Add(new PointDataList() { PointCode = "A0008", PointValue = "123", CreateTime = DateTime.Now, CreateTimeTicks = DateTime.Now.Ticks, Timestamp = DateTime.UtcNow });
            influx.WriteMeasurements(Lsts);

            //条件查询
            var stim = DateTime.Now.AddHours(-12);
            var etim = DateTime.Now;
            var longs = etim.ToLong();
            var exp = Expressionable.Create<PointDataList>()
                 .And(it => it.PointCode == "A0006")
                 .And(it => it.CreateTimeTicks >= stim.Ticks)
                 .And(it => it.CreateTimeTicks < etim.Ticks)
                 .ToExpression();
            var lst = influx.QueryBy(exp, n => n.Timestamp);

            //查询所有
            var lst2 = influx.QueryAll();

            //根据条件查询分页查询
            int skip = 0;//当前第几页
            int take = 10;//每页多少条
            int count = 0;//返回总行数
            var lst3 = influx.QueryBy(exp, n => n.Timestamp, skip, take, out count);
        }
    /// <summary>
    /// 类似于关系数据库的表名 点位表
    /// </summary>
    [Measurement("PointDataList")]
    public class PointDataList
    {
        /// <summary>
        /// 标签 点位名称
        /// </summary>
        [Column("PointCode", IsTag = true)]
        public string PointCode { get; set; }
        /// <summary>
        /// 普通字段 点位值
        /// </summary>
        [Column("PointValue")]
        public string PointValue { get; set; }
        /// <summary>
        /// 创建时间的Ticks
        /// </summary>
        [Column("CreateTimeTicks")]
        public long CreateTimeTicks { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        [Column("CreateTime")]
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// UTC时间
        /// </summary>
        [Column(IsTimestamp = true)]
        public DateTime Timestamp { get; set; }
    }

  

    }
    #endregion
}

  

标签:C#,V2.5,InfluxDB,DateTime,client,var,using,Now,public
From: https://www.cnblogs.com/XiaoRuLiang/p/16994599.html

相关文章

  • mvc中,js 如何直接使用后端参数
    问题比如后端传了一个boolean类型的参数,js如果直接使用这个参数,比如这么写就是错的if(${redevice}){document.getElementById('redevice').checked=true;}......
  • npm install初始化出现问题: npm ERR! Unsupported URL Type "workspace:": workspace:
    1.在拉取项目之后,npminstall初始化报错npmERR!UnsupportedURLType"workspace:":workspace:*2.检查package.json中是否出现过[workspace:],如果有,并出现上述问......
  • AWS AppSync 添加 自定义 坐标查询 V2
    res.vtl#set($items=[])#foreach($entryin$context.result.hits.hits)#if(!$foreach.hasNext)#set($nextToken=$util.base64Encode($util.toJso......
  • Industrial wifi6 router/wifi6-Qualcomm-IPQ6010/IPQ6018-Wallys
    MT7915/IPQ6000/IPQ6018/IPQ6010/IPQ4019/IPQ4029/IPQ5018/IPQ8072/IPQ8072A/IPQ8074/IPQ8074A/QCN6024/QCN9074/QCN9072/QCN9024/IPQ4018/IPQ4028/AR9223/QCA9880/QCA9882/......
  • DevExpress控件之GridControl控件
    ​​DevExpress控件之GridControl控件(代码篇)​​ ​​1. 设置数据源:​​   ​​string​​​​​sql=​​​​"selectfid,fnamefromdual"​​​​;......
  • supervisor+gunicorn+uvicorn部署fastapi项目
    一、编写一个项目本项目是在虚拟环境下的:先启动虚拟环境:source.venv/bin/activate。(创建虚拟环境自己去找) 项目用于演示,所以非常简单,......
  • ConcurrentHashMap
    ​JDK5中添加了新的concurrent包,相对同步容器而言,并发容器通过一些机制改进了并发性能。因为同步容器将所有对容器状态的访问都串行化了,这样保证了线程的安全性,所以这种......
  • 线程间协作的两种方式:wait、notify、notifyAll和Condition
    在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作。比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待......
  • 二阶段目标检测网络-Cascade RCNN 详解
    摘要1,介绍1.1,FasterRCNN回顾1.2,mismatch问题2,实验分析2.1,改变IoU阈值对Detector性能的影响2.2,提高IoU阈值的影响2.3,和IterativeBBox比较3,网络结构参考......
  • (1)SpringMVC前传
    在我们熟知的建立在三层结构(表示层、业务逻辑层、持久层)基础之上的J2EE应用程序开发之中,表示层的解决方案最多。因为在表示层自身的知识触角很多,需要解决的问题也不少,这也就......