当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js AsyncLocalStorage用法及代码示例


类:AsyncLocalStorage

历史
版本变化
v16.4.0

AsyncLocalStorage 现在是稳定的。以前,它是实验性的。

v13.10.0、v12.17.0

添加于:v13.10.0、v12.17.0

此类创建通过异步操作保持一致的存储。

虽然您可以在node:async_hooks 模块之上创建自己的实现,但应该首选AsyncLocalStorage,因为它是一种高性能且内存安全的实现,其中涉及不明显实现的显著优化。

以下示例使用 AsyncLocalStorage 构建一个简单的记录器,该记录器为传入的 HTTP 请求分配 ID,并将它们包含在每个请求中记录的消息中。

import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
//   0: start
//   1: start
//   0: finish
//   1: finishconst http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
//   0: start
//   1: start
//   0: finish
//   1: finish

AsyncLocalStorage 的每个实例都维护一个独立的存储上下文。多个实例可以安全地同时存在,而不会干扰彼此的数据。

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 AsyncLocalStorage。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。