influxDB 0.9 C# 读写类


    目前influxdb官网推荐的C#读写类是针对0.8版本的,截至本文写作之前,尚未发现有针对0.9的读写类。

    我使用influxdb的是用于保存服务器的运行数据,程序需要以windows service的形式运行。

    influxdb提供了基于http的接口。一开始我使用的是httpClient来作为http客户端,但是发现程序以windows serive的形式运行的时候,居然无法发起http请求!而当windows service附在其它进程上,或者以window form形式运行时,却是正常的。试了多种方法,包括更改windows service的运行权限、更改.net的运行时版本、更换机器等,都不行,百思不行其解,说多了都是泪。园里的大大们,谁能告诉我为什么?最后只能将http客户端换成WebClient。

    回到正题,本读写类对influxdb提供的http api进行了封装。目前实现了:

  (1)读数据。

  (2)写数据。包括批量写入。

  (3)身份认证。

代码

核心类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Net.Http;
 7 using System.Security.Cryptography.X509Certificates;
 8 
 9 public class InfluxDBClient
10 {
11     string _baseAddress;
12     string _username;
13     string _password;
14 16 
17     /// <summary>
18     /// 构造函数
19     /// </summary>
20     /// <param name="baseAddress"></param>
21     /// <param name="username"></param>
22     /// <param name="password"></param>
23     public InfluxDBClient(string baseAddress, string username, string password)
24     {
25         this._baseAddress = baseAddress;
26         this._username = username;
27         this._password = password;
28     }
29 
30 
31 
32     /// <summary>
33     ///34     /// </summary>
35     /// <param name="database"></param>
36     /// <param name="sql"></param>
37     /// <returns></returns>
38     public string Query(string database, string sql)
39     {
40         string pathAndQuery = string.Format("/query?db={0}&q={1}", database, sql);
41         string url = _baseAddress + pathAndQuery;
42 
43         string result = HttpHelper.Get(url, _username, _password);
44         return result;
45     }
46 
49 
50 
51 
52     /// <summary>
53     ///54     /// </summary>
55     /// <param name="database"></param>
56     /// <param name="sql"></param>
57     /// <returns></returns>
58     public string Write(string database, string sql)
59     {
60         string pathAndQuery = string.Format("/write?db={0}&precision=s", database);
61         string url = _baseAddress + pathAndQuery;
62 
63         string result = HttpHelper.Post(url, sql, _username, _password);
64         return result;
65     }
66 }

 

http帮助类

 1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Net;  5 using System.Text;  6 using System.Threading.Tasks;  7   9 public class HttpHelper 10 { 13 /// <summary> 14 /// 15 /// </summary> 16 /// <param name="uri"></param> 17 /// <param name="username"></param> 18 /// <param name="password"></param> 19 /// <returns></returns> 20 public static string Get(string uri, string username, string password) 21  { 22 string result = string.Empty; 23 24 WebClient client = new WebClient(); 25 26 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) 27  { 28 client.Credentials = GetCredentialCache(uri, username, password); 29 client.Headers.Add("Authorization", GetAuthorization(username, password)); 30  } 31 return client.DownloadString(uri); 32  } 33 34 35 36 37 /// <summary> 38 /// 39 /// </summary> 40 /// <param name="uri"></param> 41 /// <param name="paramStr"></param> 42 /// <param name="username"></param> 43 /// <param name="password"></param> 44 /// <returns></returns> 45 public static string Post(string uri, string paramStr, string username, string password) 46  { 47 string result = string.Empty; 48 49 WebClient client = new WebClient(); 50 51 // 采取POST方式必须加的Header 52 client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 53 54 byte[] postData = Encoding.UTF8.GetBytes(paramStr); 55 56 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) 57  { 58 client.Credentials = GetCredentialCache(uri, username, password); 59 client.Headers.Add("Authorization", GetAuthorization(username, password)); 60  } 61 62 byte[] responseData = client.UploadData(uri, "POST", postData); // 得到返回字符流 63 return Encoding.UTF8.GetString(responseData);// 解码 64  } 65 66 67 68 69 70 71 private static CredentialCache GetCredentialCache(string uri, string username, string password) 72  { 73 string authorization = string.Format("{0}:{1}", username, password); 74 CredentialCache credCache = new CredentialCache(); 75 credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password)); 76 return credCache; 77  } 78 79 80 81 82 private static string GetAuthorization(string username, string password) 83  { 84 string authorization = string.Format("{0}:{1}", username, password); 85 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); 86  } 87 88 89 90 }

日期转换的扩展方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 
 8 public static class Extentions
 9 {
10 
11     /// <summary>
12     /// 将当前时间转换成unix时间戳形式
13     /// </summary>
14     /// <param name="datetime"></param>
15     /// <returns></returns>
16     public static long ToUnixTimestamp(this DateTime datetime)
17     {
18         return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
19     }
20 
21 }

注:influxdb的日期使用的是unix时间戳格式

 

使用方法

        InfluxDBClient client = new InfluxDBClient("http://110.124.149.123:8086", username, password);
        long timestamp = DateTime.Now.ToUnixTimestamp();
        List<string> list = new List<string>();
        list.Add(string.Format("requestsQueued value={0} {1}", 20, timestamp));    //requestsQueued为指标的名称
        list.Add(string.Format("currentConnections value={0} {1}", 10, timestamp));
        list.Add(string.Format("bytesReceivedPerSec value={0} {1}", 100, timestamp));
        string sql = string.Join("\n", list);
        var result = client.Write("server01", sql);

 

需要进一步完善的地方

    (1)目前读取数据的时候,当前返回的是一个字符串,这只是body中的信息,而其http头中还有部分信息。需要对这些信息进行封装。

    (2)在使用这个类的时候,需要对influxdb的读写语法有一定的了解。而理想状态下,是不需要这样的。比如写数据,使用者只需要传入一个键值对(指标,指标值),而不需要传入类似于“requestsQueued value={0} {1}"这样的包含了influxdb语法的字符串。

    有兴趣的同学可以对这个类进行改写。

 

适用范围

    如果只是为了配合grafana来使用的话,这个读写类足够了,因为grafana可以直接读取influxdb的数据,我们要做的只是往influxdb中写入数据。

 

 

参考资料

InfluxDB Docs v0.8    https://influxdb.com/docs/v0.8/introduction/overview.html

InfluxDB.Net             https://github.com/ziyasal/InfluxDB.Net

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM