介绍
Node-RED 是一个基于 Node.js 的编程工具,可以让用户通过拼接节点来快速构建物联网和物联网应用程序。而 CrateDB 是一个基于 SQL 的面向实时应用的分布式数据库。
node-red-contrib-cratedb
是一个 Node-RED 插件,可以让用户将数据存储在 CrateDB 数据库中。本文将基于详细的示例代码,介绍如何使用该插件。
安装
可以通过 npm 安装该插件:
npm install node-red-contrib-cratedb
配置
连接配置
在 Node-RED 的管理界面上,可以通过“节点”面板找到 node-red-contrib-cratedb
节点,将其放置在程序工作区。然后右击它,选择“编辑”菜单,进入节点的编辑界面。
在编辑界面的“连接”面板上,可以配置 CrateDB 数据库的连接信息,包括连接的主机名、端口、数据库名称、用户名和密码。
SQL 配置
在编辑界面的“SQL”面板上,可以配置 SQL 语句和参数。可以输入自定义的 SQL 语句,也可以使用占位符的方式设置参数。
示例代码
以下示例代码包含了如何在 Node-RED 中使用 node-red-contrib-cratedb
插件。
向 CrateDB 插入数据
[{"id":"2cb2e14b.dd725a","type":"debug","z":"2fe89fbd.541c34","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":620,"y":240,"wires":[]},{"id":"ee6336f9.47d37","type":"inject","z":"2fe89fbd.541c34","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"name\":\"john\",\"age\":24}","payloadType":"json","x":240,"y":240,"wires":[["d1a76c10.57dc1"]]},{"id":"d1a76c10.57dc1","type":"function","z":"2fe89fbd.541c34","name":"Insert Data","func":"var name = msg.payload.name;\nvar age = msg.payload.age;\n\nmsg.topic = \"INSERT INTO users (name, age) VALUES (?, ?)\";\nmsg.params = [ name, age ];\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":430,"y":240,"wires":[["1d6f62af.352aa"]]},{"id":"1d6f62af.352aa","type":"node-red-contrib-cratedb","z":"2fe89fbd.541c34","name":"","connection":"","sql":"","params":"","outputformat":"object","x":530,"y":240,"wires":[["2cb2e14b.dd725a"]]}]
从 CrateDB 中获取数据
[{"id":"d3923396.0e6e18","type":"http in","z":"2fe89fbd.541c34","name":"","url":"/users","method":"get","upload":false,"swaggerDoc":"","x":200,"y":260,"wires":[["19dcce43.697d55"]]},{"id":"19dcce43.697d55","type":"function","z":"2fe89fbd.541c34","name":"Get All Users","func":"msg.topic = \"SELECT * FROM users\";\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":380,"y":260,"wires":[["1d6f62af.352aa"]]},{"id":"d5c139b7.5a5e08","type":"debug","z":"2fe89fbd.541c34","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":740,"y":260,"wires":[]},{"id":"1d6f62af.352aa","type":"node-red-contrib-cratedb","z":"2fe89fbd.541c34","name":"","connection":"","sql":"","params":"","outputformat":"object","x":570,"y":260,"wires":[["d5c139b7.5a5e08"]]}]
指导意义
node-red-contrib-cratedb
插件是一个极其实用的工具,可以让用户轻松地将数据存储在 CrateDB 数据库中,适用于物联网和物联网应用程序的快速构建。
通过本文的介绍,读者可以深入了解该插件的使用方法。同时,读者可以将该插件应用到实际项目中,进一步提高对 Node-RED 的熟练程度,为使用 Node-RED 构建物联网和物联网应用程序打下基础。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6005534981e8991b448d0856