1、安装和使用Influxdb
安装部分网上资料比较多,也讲的比较详细,请自行百度。
下面大概讲下InfluxDB的写入和读取数据的方法。
我使用了InfluxData.Net包。
工具-》NuGet包管理器-》管理解决方案的NuGet程序包-》浏览-》输入InfluxData.Net。
安装好之后就可以写代码了
其中注意几点坑
1、InfluxDB的time格式是世界标准时区时间,所以我在其基础上加了8小时,具体请看下面的代码。
2、插入和查询数据时,语句中不能包含引号“”、‘’,这和InfluxDB的行协议有关,如果插入的数据中包含引号,一定要进行转义。例如 \"weather\"
3、查询后的数据格式和其他数据库不一致,格式如下。我提供了两种解析方法(输出List或json字符串)
代码如下:
using InfluxData.Net.Common.Enums;
using InfluxData.Net.InfluxDb;
using InfluxData.Net.InfluxDb.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Threading.Tasks;
using InfluxData.Net.Common.Helpers;
namespace test
{
public class InfluxDbRepository
{
private readonly InfluxDbClient _clientDb;
private readonly IInfluxDbConfig _influxDbConfig;
public InfluxDbRepository(IInfluxDbConfig influxDbConfig)
{
_influxDbConfig = influxDbConfig;
var influxUrl = _influxDbConfig.Get().InfluxUrl;
var influxUser = _influxDbConfig.Get().InfluxUser;
var influxPwd = _influxDbConfig.Get().InfluxPwd;
//创建InfluxDbClient实例
_clientDb = new InfluxDbClient(influxUrl, influxUser, influxPwd, InfluxDbVersion.Latest);
}
/// <summary>
/// 写入单个对象
/// </summary>
/// <param name="entities"></param>
/// <param name="baseLog">基本信息</param>
/// <returns></returns>
public async System.Threading.Tasks.Task InsertAsync(BaseLog baseLog)
{
try
{
var tags = new Dictionary<string, object>();
var fields = new Dictionary<string, object>();
var propertyInfos = ForeachClassHelper.ForeachClassProperties<BaseLog>(baseLog);
foreach (var item in propertyInfos)
{
fields.Add(item.Name, item.GetValue(baseLog, null));
}
var pointModel = new Point()
{
Name = _influxDbConfig.Get().TableName,//表名
Tags = tags,
Fields = fields,
Timestamp = DateTime