使用 InfluxDB

在配置服务中注册连接

在使用 InfluxDB 前,请先在配置服务中注册连接参数,可参考下图:

xx

上图注册了一个连接,名称是 InfluxDBTest




创建客户端实例

根据“连接名称”创建客户端实例 (示例代码使用了上图中的连接名称)

InfluxClient client = InfluxClient.Create("InfluxDBTest");

对于SaaS场景,可以采用下面的方式创建InfluxClient实例

InfluxClient client = InfluxClient.CreateTenant("tenantId");




写入数据到 InfluxDB

public static async Task Test_Write()
{
	// 生成要写入的测试数据
	List<RequestCount> list = CreateTestData();

	// 创建InfluxDB的客户端实例,Create方法的参数是一个“连接名称”,它已在配置服务中注册为数据库连接
	InfluxClient client = InfluxClient.Create("InfluxDBTest");

	// 执行插入操作
	await client.InsertAsync(list);
}

示例代码中数据结构的定义

public sealed class RequestCount
{
	[TagField]
	public string AppName { get; set; }
	[TagField]
	public string HostName { get; set; }

	[ValueField]
	public int Count { get; set; }

	[ValueField]
	public int Error { get; set; }

	[ValueField]
	public int Slow { get; set; }

	[ValueField]
	public int AvgTime { get; set; }

	[TimeField]
	public DateTime CreateTime { get; set; }
}




从 InfluxDB 中查询数据

示例-1--无参数

public static async Task Test_Query()
{
	// 查询最近 6 小时数据,30分钟为一个采样频率
	string query = @$"select sum(Count) as Count, sum(Error) as Error from RequestCount 
				WHERE AppName='TestApp0' and time > now() - 6h group by time( 30m )";

	// 执行查询
	InfluxClient client = InfluxClient.Create("InfluxDBTest");
	DataTable table = await client.ToTableAsync(query);

	Console.WriteLine(table.ToJson(JsonStyle.Indented));
}

示例-2--参数化查询

public static async Task Test_Query2()
{
	DateTime today = DateTime.Today;
	long start = today.GetNanoTime();
	long end = today.AddHours(6).GetNanoTime();
	
	// 带有占位参数的查询, $start, $end, 1个小时为一个采样频率
	string query = @$"select sum(Count) as Count, sum(Error) as Error from RequestCount 
				WHERE time >= $start and time < $end group by time( 1h )";

	var args = new { start, end };  // 查询参数

	// 执行查询
	InfluxClient client = InfluxClient.Create("InfluxDBTest");
	DataTable table = await client.ToTableAsync(query, args);

	Console.WriteLine(table.ToJson(JsonStyle.Indented));
}



下面这些InfluxDB查询都是有效的

select * from RequestCount 
WHERE AppName='TestApp0'  ORDER BY time DESC LIMIT 300

select * from RequestCount 
WHERE time >= '2020-10-15 00:00:00' and time < '2020-10-16 00:00:00' ORDER BY time DESC LIMIT 300

select sum(Count) as Count, sum(Error) as Error from RequestCount 
WHERE time >= '2020-10-15 00:00:00' and time < '2020-10-16 00:00:00' and AppName='TestApp0' group by time(1h)

select sum(Count) as Count, sum(Error) as Error from RequestCount 
WHERE AppName='TestApp0' and time > now() - 24h group by time(1h)



InfluxDB查询语法参考链接: https://docs.influxdata.com/influxdb/v1.8/query_language/




在查询服务中使用 InfluxDB

在查询服务中创建服务接口可参考下图:

xx


说明:

  • SQL中的参数名以 $ 开头
  • 如果需要查看 InfluxDB 的原始响应,调用时请指定:x-result-format=raw

数据查询服务支持以下返回格式:

  • json (默认值)
  • xml
  • xml2
  • csv
  • excel
  • raw