@gatehub/microkit

中文文档
0.16.0发布于 2026/11/13MITCommonJS近 30 天下载 2204

公开微服务工具包

中文使用文档
文档目录4 节
  1. 安装
  2. 使用量
  3. 追踪
  4. 许可证

微基特 NPM version

Node.js 微服务工具包

用于微服务的抽象工具包,让节点开发者再次快乐.

安装

$ npm install --save @gatehub/microkit

使用量

var MicroKit = require('microkit');

// Instantiate MicroKit
var microkit = new MicroKit({
  name: 'myAwesomeService',
  environment: 'production',
  logLevel: 'info',
  catchGlobal: true, // catch global errors
  queue: {
    name: 'amqp',
    url: "amqp://localhost",
    queue: 'myAwesomeService',
    socketOptions: {heartbeat: 5, channelMax: 100}, // optional, overrides url params; heartbeat defaults to 5, channelMax to the broker's limit; other keys (e.g. TLS ca/cert) are passed to the socket
    reconnectTimeInSeconds: 5, // optional, values <= 0 fall back to the default
    publishTimeout: 5000 // optional, ms, default for the per-publish `timeout` option; a timed out message is dropped if not yet sent, but may still be delivered if it was already awaiting the broker's confirm
  }, // queue provider config
  error: {name: 'sentry', url: "https://dd..ba:[email protected]/24343"} // error reporter config
});

/** or for development it will log on stdout
 *  var microkit = new MicroKit({name: 'myAwesomeService'});
 **/

// Logging
microkit.logger.debug('message', {key: 'value'});
microkit.logger.info('message', {key: 'value'});
microkit.logger.warn('message', {key: 'value'});
microkit.logger.fatal(new Error("some error"));
microkit.logger.error('message', {key: 'value', err: new Error("some error")});

var logger = microkit.logger.create('componentName', {some: 'context'});
logger.info('message', {key: 'value'});

// Queue
microkit.queue.publish({key: 'value'}, {some: 'data'});
microkit.queue.publish({key: {key: 'value'}, message: {key: 'value'}});
// handlers always get the message body and the event
microkit.queue.subscribe({key: 'value'}, (data, event) => {
  console.log("message", data);
  console.log("headers", event.headers);         // {key: 'value'}
  console.log("routing key", event.routingKey);  // '' for headers messages
  console.log("id", event.id);                   // headers if any, otherwise the routing key
});

// Error reporting
microkit.error.capture(new Error('some error'));

// Metrics
microkit.metrics.send('some.metric', 10, {tag1: 'value', tag2: 'value2'});

// Exit handling
microkit.onExit(() => server.close());

// Express integration (logging, error reporting)
app.use(microkit.express.preHandler); // before all middlewares
app.use(microkit.express.postHandler); // after middlewares

// config
microkit.config.get('key.value');

// common errors
const MyConnectionError = microkit.errors.ConnectionError.extend({
  name: 'MyConnectionError'
});
throw new MyConnectionError({code: 'database_error', error: err});

追踪

为了能够追踪,它需要包含在开始脚本中,以便在其他一切之前被加载:

    "start": "node --require @gatehub/microkit/lib/telemetry.js dist/server.js",

配置

配置参数将从环境变量中获取. 需要以下环境变量:

# The destination to send traces to
  OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
# Your service name - it will be listed as such in the traces
  OTEL_SERVICE_NAME=my-service-name
# Log level - info is fine unless debugging
  OTEL_LOG_LEVEL=info
# Enable tracing database requests
  TRACING_SQL_ENABLE=true

对于本地和服务特定配置,需要两个配置文件:

  • .tracing.json : 运行时配置 excludeRoutes 财务报告和审定财务报表 ignoredOutgoingHosts (其他参数应设置为env vars)
  • dev.tracing.json: 本地配置(所有参数)

从环境中获取的任何配置变量都将优先于配置文件.

示例

{
  "otlpEndpoint": "http://localhost:4318/v1/traces", // optional, dev 
  "otelServiceName": "service-name", // optional, dev
  "otelLogLevel": "info", // optional, dev
  "otelSqlTracingEnabled": true, // optional, dev, default false
  "otelAmqpTraceContentEnabled": true, // optional, dev, default false
  "excludeRoutes": [
    "/healthz/liveness",
    "/metricz"
  ],
  "ignoredOutgoingHosts": [
  ]
}

使用量

任何函数都可以用 TraceSpan来附加到跟踪上. getActiveSpan() 可用于获得当前活动跨度. spanObjectStringify() 可用于将任何对象串入适当的格式.

    @microkit.tracing.TraceSpan()
    public async someFunction(payload: Payload) {
        const span = microkit.tracing.getActiveSpan()
        span?.setAttribute(
            'some-attribute-name-payload',
            microkit.tracing.spanObjectStringify(payload),
        );

        ... function body
    }

许可证

麻省理工学院 GateHub 网络

版本与发布记录

@gatehub/microkit 共发布 17 个版本,首次发布于 2019/08/01;过去 12 个月发布了 14 个版本。

版本发布日期距今
0.16.0latest2026/11/132 天前
0.15.12026/11/105 天前
0.15.02026/11/096 天前
0.14.12026/11/069 天前
0.13.162026/11/069 天前
0.13.152026/09/171 个月前

关于 @gatehub/microkit 的常见问题

@gatehub/microkit 是什么?

公开微服务工具包

如何安装 @gatehub/microkit?

在项目目录运行 npm install @gatehub/microkit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@opentelemetry/api(~1.10.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gatehub/microkit 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/gatehub__microkit 是否存在。

@gatehub/microkit 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gatehub/microkit 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gatehub/microkit 可以商用吗?

@gatehub/microkit 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gatehub/microkit 的下载量有多少?

根据 npm 官方下载统计,@gatehub/microkit 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,204 次,日均约 73 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gatehub/microkit 还在维护吗?

最新版本 0.16.0 发布于 2026/11/13(2 天前);至今共发布 17 个版本,其中过去 12 个月发布了 14 个;首次发布于 2019/08/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。