websocket 2 rest api
需要开发一个prometheus 的exporter 使用jmespath 获取对应metrics的数据,并进行转换处理,但是因为那个服务
提供的接口是通过websoket 的实时api,所以基于node 进行了简单的包装处理,暴露为一个直接可以使用的rest api
同时保留了数据的实效性
实现技术
很简单,通过express 暴露一个rest api,通过websocket client 连接已有websocket 服务,并使用全局变量存储数据即可
后边对应的exporter 直接获取数据进行处理就可以了
项目结构
- 代码结构
├── Dockerfile
├── README.md
├── app.env
├── docker-compose.yaml
├── index.js
├── package.json
- 代码说明
Dockerfile
FROM node:alpine
WORKDIR /app
COPY . /app
LABEL NORE="ws 2 rest"
ENV NODE_ENV=production
ENV WSADDRESS=ws://localhost:7890/
LABEL AUTHOR="1141591465@qq.com"
EXPOSE 3000
RUN yarn
CMD [ "yarn", "start"]
index.js: 核心处理代码,和简单,就是包装了websocket 服务
const express = require('express')
const app = express()
var realtimeMetrics ={};
const WebSocketClient = require('websocket').client;
// 通过环境变量配置websocket 服务的地址
const wsAddress = process.env.WSADDRESS || "ws://localhost:7890/"
const client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
client.onopen = function() {
console.log('WebSocket Client Connected');
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
realtimeMetrics = message.utf8Data;
}
});
});
client.connect(wsAddress);
app.get('/', function (req, res) {
res.contentType("application/json")
res.send(realtimeMetrics)
})
app.listen(3000)
pacakge.json 内容: 主要是npn 包的引用以及npm script 配置,这个包含了几个多余的依赖,但是不影响使用
可以直接删除
{
"dependencies": {
"express": "^4.16.4",
"jmespath": "^0.15.0",
"node-fetch": "^2.3.0",
"websocket": "^1.0.28"
},
"scripts": {
"start":"node index.js"
}
}
docker-compose.yaml
version: "3"
services:
ws2rest:
image: dalongrong/simplews2rest
build: ./
ports:
- "3000:3000"
env_file:
- app.env
app.env : 主要是方便扩展的
WSADDRESS=ws://server:port/
使用此服务的demo
- docker-compose 文件
version: "3"
services:
metrics:
image: dalongrong/promethues-jmespath-exporter
volumes:
- "./conf/config.yaml:/etc/prometheus-jsonpath-exporter/config.yml"
ports:
- "9158:9158"
command: /etc/prometheus-jsonpath-exporter/config.yml
ws2rest:
image: dalongrong/simplews2rest
environment:
- "WSADDRESS=ws://server:7890/"
ports:
- "3000:3000"