欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

解决方案:Nodejs 微服务的 APM 功能

最编程 2024-04-17 07:34:59
...

在今天的这篇文章中,我来简单地介绍如何为 Nodejs 应用实现 APM。关于如何安装 Elasticsearch, Kibana 及 APM server,请参阅我之前的文章“应用程序性能监控/管理(APM)实践”。在这篇文章中,我们来简单介绍一下需注意的一些地方。

我们在进行下面的工作之前,先启动 Elasticsearch, Kibana 及 APM server。

 

如何配置

我们打开 Kibana:

点击上面的 Add APM 按钮:

我们在 APM agents 里找到 Nodejs,并安装上面的要求进行安装和配置。如果你还没有自己的 nodejs 应用的话,请参考我一个示例的 nodejs 应用:

git clone https://github.com/liu-xiao-guo/apm-zipcode-microservice

这是一个很简单的测量两个 zipcode 直接的距离的一个微服务应用。我们可以在 terminal 中打入如下的命令来进行安装及运行:

npm install
npm start

我们可以在浏览器中输入如下的地址

http://localhost:3000/distance/84010/97229

我们将看到如下的输出:

{"distance":638.174}

我们在浏览器地址中输入如下的地址

http://localhost:3000/distance/84010/92001

我们可以看到如下的输出:

{"distance":-1}

我们现在看一下 nodejs 的第一个文件 index.js:

index.js

// Add this to the VERY top of the first file loaded in your app
var apm = require('elastic-apm-node').start({
    // Override service name from package.json
    // Allowed characters: a-z, A-Z, 0-9, -, _, and space
    serviceName: 'zipcode service',
  
    // Use if APM Server requires a token
    secretToken: '123456',
  
    // Set custom APM Server URL (default: http://localhost:8200)
    serverUrl: 'http://localhost:8200'
  })

var express = require('express')
var app = express();
var port = process.env.PORT || 3000;

var routes = require('./api/routes');
routes(app);
app.listen(port, function() {
    console.log('Server started on port: ' + port);
});

在这里我们必须说明的是,我们也可以通过 OS 的环境变量来配置 serviceName, serverUrl,而且通过环境变量的配置将具有更高的优先级:

export ELASTIC_APM_SERVICE_NAME=my_application
export ELASTIC_SERVER_URL=http://localhost:8200
export ELASTIC_APM_ENVIRONMENT=production

我们也可以通过在当前项目根目录中的 elastic-apm-node.js 文件来配置,比如:

elastic-apm-node.js

module.exports = {
    serviceName: 'my-application',
    serviceUrl: 'http://localhost:8200',
    environment: 'production'
}

如果我们使用上面的方法,那么就不需要在如下的代码中指定 serviceName, serviceUrl 等。我们可以注意这个文件的最上面的部分:

// Add this to the VERY top of the first file loaded in your app
var apm = require('elastic-apm-node').start({
    // Override service name from package.json
    // Allowed characters: a-z, A-Z, 0-9, -, _, and space
    serviceName: 'zipcode service',
  
    // Use if APM Server requires a token
    secretToken: '123456',
  
    // Set custom APM Server URL (default: http://localhost:8200)
    serverUrl: 'http://localhost:8200'
  })

这个部分其实就是要求我们从 Kibana 界面中拷贝过来并修改的部分。

我们切换到 Kibana 的 APM 应用界面:

点击上面的 zipcode service:

点击 GET /distance/:zipcode1/:zipcode2 链接:

这样我们就可以看到整个 API 的调用情况。

推荐阅读