當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。