如何在NodeJ中使用AWS X-Ray?

时间:2018-11-15 09:12:36

标签: node.js amazon-web-services express aws-sdk-nodejs

我正在尝试使用aws-xray-sdk来获取我的应用程序的痕迹,
我写了三个API,
1.调用AWS S3服务( / traceS3
2.对外部端点进行HTTP调用,即google.com( / traceHttp
3.对本地安装的MySql数据库( / traceMysql

进行数据库调用

还安装了AWS X-Ray Daemon locally
并使用aws-cli进行AWS配置,然后使用以下命令运行守护程序(我正在使用Ubuntu)-

/usr/bin/xray -o -n ap-southeast-2

我是指以下资源-
1. aws x-ray tracing breaks on outgoing requests in Node.js
2. https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html

守护程序成功运行,但未发送所有API的数据,
它仅发送/traceS3/traceMysql API的数据。

以下是正在运行的代码-

var AWSXRay = require('aws-xray-sdk');
var AWS = AWSXRay.captureAWS(require('aws-sdk'));
var mysql = AWSXRay.captureMySQL(require('mysql'));

var express = require('express');
var app = express();

var http = AWSXRay.captureHTTPs(require('http'));
app.use(AWSXRay.express.openSegment('X-Ray-Node-Example'));

AWS.config.update({region: 'ap-southeast-2'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "nodejs",
    port: 3306
});

con.connect(function (err) {
    if (err) throw err

});

app.get('/traceS3', function(req,res){

    // Call S3 to list current buckets
    s3.listBuckets(function(err, data) {
        if (err) {
            console.log("Error", err);
            res.send(err);
        } else {
            res.send(data.Buckets);
        }
    });
});

app.get('/traceHttp', function (req, res) {
    console.log("traceHttp called!\n"+req);

    http.get("http://jsonplaceholder.typicode.com/todos/1", (resp) => {
        console.log(resp);
        res.send("googlefetched")
    });
});

app.get('/traceMysql', function (req, res) {
    console.log("traceMysql called!\n"+req);

    var start = Date.now();

    var query = con.query('SELECT * FROM customer', function (err, rows, fields) {
        if (err) {
            console.log("Error Selecting : %s ", err);
        }
        else {
            var resp = [];
            function Person(id, name) {
                this.id = id;
                this.name = name;
            }

            for (var i = 0; i < rows.length; i++) {
                var id = rows[i].id;
                var name = rows[i].name;
                resp.push(new Person(id, name));
            }
            var end = Date.now();
            res.send(JSON.stringify({ "status": 200, "error": null, "response": resp, "requestTime": end - start }));
        }
    });
});

app.use(AWSXRay.express.closeSegment());
var server = app.listen(8085, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
});

有人可以修复该代码吗?

1 个答案:

答案 0 :(得分:0)

症状似乎类似于据说已在v1.2.0中修复的错误的症状

HTTP Patcher leaks response & stalls segments if no other response listener is supplied