前言
本节内容主要介绍怎么将数据存到数据库,这里我使用的是时许数据库influxdb,一个非常好用的数据库。比较适合物联网数据的存储,大家可以自行去了解一下
安装并运行influxdb
下载安装influxdb
到官网的下载目录里选择你现在的环境,我的是win10,下载一个压缩包,解压后,就可以直接用了。还是非常简单的。
-
下载链接https://portal.influxdata.com/downloads,选windows版
-
解压,目录如下
-
如果只是临时测试的话,直接就可以用了,如果有一些特殊需求,可以修改配置文件influxdb.conf
-
运行influxd.exe,如果出现下图所示说明安装成功了
运行influx.exe,可以输入命令进行测试
// 查看数据库
show database
// 创建数据库(test)
create database test
具体详细的使用,可以查看官方文档
安装influxdb节点
打开Node-Red,在节点管理当中输入influx,安装第一个即可
如何使用
最好会SQL一些基本操作
这里我展示一下基本操作,写入和读取
写入
如果没有数据库的话会报错,如果没有表的话会自动创建新的表。所以,我们需要提前创建一个以test为名的数据库
这里我向test数据库cpu表插入了一条数据,内容是
msg.payload = {
host: "serverA",
region: "cn_sh",
value: 0.64
}
return msg;
读取
刚刚通过一系列骚操作,实现了数据的写入,那么接下来就验证一下到底有没有写入,那么就再来一个骚操作读取一下这个数据
查询语句
SELECT "host", "region", "value" FROM "cpu"
根据上图得知,我们已经成功得将数据插入到数据库里了,并且成功的读取出来了,可以发现的是,influx自动添加了一个time属性,毕竟是时序数据库嘛,但是这个time有点问题。这里就需要注意一下时区问题。
案例分享
大家可以自行复制下面的代码,然后在Node-Red中导入即可。
[{"id":"3062439.217d7bc","type":"influxdb in","z":"63da8941.7cd5c8","influxdb":"22488c7e.9b0334","name":"","query":"SELECT \"host\", \"region\", \"value\" FROM \"cpu\" ","rawOutput":false,"precision":"s","retentionPolicy":"","x":1440,"y":1160,"wires":[["595395b9.6c5a4c"]]},{"id":"595395b9.6c5a4c","type":"debug","z":"63da8941.7cd5c8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":1830,"y":1160,"wires":[]},{"id":"6f59cb7d.30f5e4","type":"inject","z":"63da8941.7cd5c8","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":1110,"y":1160,"wires":[["3062439.217d7bc"]]},{"id":"15fbbf59.602201","type":"influxdb out","z":"63da8941.7cd5c8","influxdb":"22488c7e.9b0334","name":"","measurement":"cpu","precision":"","retentionPolicy":"","x":1730,"y":1080,"wires":[]},{"id":"8bfe7bf6.4a3f08","type":"inject","z":"63da8941.7cd5c8","name":"","topic":"","payload":"","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":"","x":1110,"y":1080,"wires":[["45c777b8.4030f8"]]},{"id":"45c777b8.4030f8","type":"function","z":"63da8941.7cd5c8","name":"Fields","func":"msg.payload = {\n host: \"serverA\",\n region: \"cn_sh\",\n value: 0.64\n}\nreturn msg;","outputs":1,"noerr":0,"x":1470,"y":1080,"wires":[["15fbbf59.602201"]]},{"id":"22488c7e.9b0334","type":"influxdb","z":"","hostname":"127.0.0.1","port":"8086","protocol":"http","database":"test","name":"","usetls":false,"tls":""}]