暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

influxdb 在 nodejs 中的应用

前端新视野 2019-07-24
1164

  有一些后端经验或者长期深入应用 nodejs 到大型业务中的 noder 应该对 influxdb 比较熟悉,这里我们开启一个influxdb相关的开篇。


  1、influxdb 是什么?


官网:https://www.influxdata.com/


Real-time visibility into stacks, sensors and systems


  • 用 Go 编写的

  • 无外部依赖

  • 开源

  • 分布式时序、事件和指标数据库


2、如何安装,安装什么版本?


市面上很多文档都相对比较老,官方推荐是 v1.7


安装地址如下,可以选择对应的系统环境进行安装:


https://docs.influxdata.com/influxdb/v1.7/introduction/installation/


PS:因为很多公司测服、线上等环境的 db 禁止本地访问,所以也可以在你的 mac 系统上进行安装,安装如下:


brew install influxd
ln -sfv /usr/local/opt/influxdb/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.influxdb.plist


如何你要修改一些默认端口的话,可以查看 types.go


type DataNode struct {
ID uint64 `json:"id"` // Meta store ID.
TCPAddr string `json:"tcpAddr"` // RPC addr, e.g., host:8088.
HTTPAddr string `json:"httpAddr"` // Client addr, e.g., host:8086.
HTTPScheme string `json:"httpScheme"` // "http" or "https" for HTTP addr.
Status string `json:"status,omitempty"` // The cluster status of the node.
}


几个概念:


  • measurement  相当于 table

  • tag 可选,字符串形式存在,可以当索引

  • field 必须,不能用来排序


上面铺垫了一些基础,安装等,下面结合 nodejs 中的应用,来看看如何封装


1、用什么包


https://www.npmjs.com/package/influx


const Influx = require('influx')




2、连接一个 host 的数据库:


const influx = new Influx.InfluxDB({
host: config.host,
database: config.database,
username: config.username,
password: config.password,
port: config.port,
schema: []
});


语法格式如下:


const client = new Influx.InfluxDB({
  // ... options
})


配置 options 如下:


  • host

  • database

  • username

  • password

  • port

  • schema


schema 的配置比较重要,如下:


  • measurement

  • fields

  • tags


我们可以定义类型:


const { 
STRING,
FLOAT,
INTEGER,
BOOLEAN
} = Influx.FieldType;


对一些通用字段进行定义:


const commonFields = {
times: INTEGER,
ua: STRING,
  os: STRING
}


PS:注意我们对汉子最好进行 encodeURIComponent




3、查询数据


封装一个 getData


function getData(sql{
return influx.query(sql).then(result => JSON.parse(JSON.stringify(result)));
}


参考官方文档:


https://node-influx.github.io/class/src/index.js~InfluxDB.html#instance-method-query


4、创建 db 和查询 db 混合成一个方法 initDatabase


用到了 getDatabaseNames  和 createDatabase


function initDatabase() {
return influx.getDatabaseNames()
.then((names) => {
// ... 判断逻辑
      if (...) {
return influx.createDatabase(...);
}
})
.catch((err) => {
      logger.error(`Error in creating database! -> ${config.database}`, err);
});
}


参考:


https://node-influx.github.io/class/src/index.js~InfluxDB.html#instance-method-createDatabase


https://node-influx.github.io/class/src/index.js~InfluxDB.html#instance-method-getDatabaseNames



5、上报


writePoints sends a list of points together in a batch to InfluxDB. 


async function doPerf(ops) {
await influx.writePoints([
{
measurement: ops.measurement,
fields: ops.fields,
tags: ops.tags,
},
]).catch((err) => {
logger.log('write error', err);
});


logger.log('write success', ops.measurement);
}


参考:


https://node-influx.github.io/class/src/index.js~InfluxDB.html#instance-method-writePoints


6、常见的错误


数据库连接超时:


{ Error: Request timed out
[0] at new ServiceNotAvailableError (***/node_modules/influx/lib/src/pool.js:37:28


源码片段:


req.on(
'timeout',
once(() => {
this._handleRequestError(
new ServiceNotAvailableError('Request timed out'),
host,
options,
callback,
);
}),
);



本文只是一个开篇,后面会介绍和推荐一些实战经验总结之类的文章


文章转载自前端新视野,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论