在Ubuntu环境中 InfluxDB的读写

100人浏览   2024-09-30 10:03:38

准备测试一下InfluxDB和Netcore的集成。

  • 安装InfluxDB

在Ubuntu环境中,更新源

curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -
source /etc/lsb-release
echo "deb https://repos.influxdata.com/${DISTRIB_ID,,} ${DISTRIB_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

安装

sudo apt-get update && sudo apt-get install influxdb
sudo service influxdb start

启动InfluxDB shell

$ influx -precision rfc3339
Connected to http://localhost:8086 version 1.2.x
InfluxDB shell 1.2.x
>

创建一个数据库

> CREATE DATABASE mydb
>
  • InfluxDBHelper类

构造函数

public InfluxDataHelper()

{

//连接InfluxDb的API地址、账号、密码

var infuxUrl = "http://172.16.1.147:8086/";

var infuxUser = "admin";

var infuxPwd = "admin";

//创建InfluxDbClient实例

clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);

}

读取

public async Task<object> GetData(string strSQL)

{

try

{

List<string> queries = new List<string>();

queries.Add(strSQL);

//从指定库中查询数据

var response = await clientDb.Client.QueryAsync(queries, dbName);

//得到Serie集合对象(返回执行多个查询的结果)

var series = response.ToList();

//取出第一条命令的查询结果,是一个集合

var list = series[0].Values;

return list;

}catch(Exception ex)

{

return ex.Message;

}

}

写入

public async void AddData(string strTable, Dictionary<string, object> tags, Dictionary<string, object> fields)

{

//基于
InfluxData.Net.InfluxDb.Models.Point实体准备数据

var point_model = new Point()

{

Name = strTable,

Tags = tags,

Fields = fields,

Timestamp = DateTime.UtcNow

};

//从指定库中写入数据,支持传入多个对象的集合

var response = await clientDb.Client.WriteAsync(point_model, dbName);

}

  • Controller中调用

[HttpPost]

public JsonResult Get(string strSQL)

{

APIResult res = new APIResult();

try

{

int i = 0;

InfluxDataHelper helper = new InfluxDataHelper();

Task<object> obj = helper.GetData(strSQL);

res.Data = obj;

res.Code = 200;

}

catch (Exception ex)

{

res.Code = 500;

res.ErrorMsg = ex.Message;

}

return new JsonResult(res);

}

测试结果:



值得期待一个玩意,改天需要看看性能如何

相关推荐