類: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: finish
const 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
的每個實例都維護一個獨立的存儲上下文。多個實例可以安全地同時存在,而不會幹擾彼此的數據。
相關用法
- Node.js AsyncLocalStorage.enterWith(store)用法及代碼示例
- Node.js AsyncLocalStorage.exit(callback[, ...args])用法及代碼示例
- Node.js AsyncLocalStorage.run(store, callback[, ...args])用法及代碼示例
- Node.js AsyncResource用法及代碼示例
- Node.js AsyncHook.enable()用法及代碼示例
- Node.js AbortController用法及代碼示例
- Node.js AbortSignal.reason用法及代碼示例
- Node.js MySQL AVG()用法及代碼示例
- Node.js ServerHttp2Stream http2stream.pushStream(headers[, options], callback)用法及代碼示例
- Node.js http2.Http2ServerRequest request.url用法及代碼示例
- Node.js request.socket用法及代碼示例
- Node.js assert.notEqual(actual, expected[, message])用法及代碼示例
- Node.js tlsSocket.authorized用法及代碼示例
- Node.js zlib.deflateRaw()用法及代碼示例
- Node.js http.IncomingMessage message.rawHeaders用法及代碼示例
- Node.js Console用法及代碼示例
- Node.js GM transparent()用法及代碼示例
- Node.js URL.protocol用法及代碼示例
- Node.js http.Agent.reuseSocket(socket, request)用法及代碼示例
- Node.js fs.filehandle.datasync()用法及代碼示例
- Node.js socket.bind()用法及代碼示例
- Node.js v8.getHeapSpaceStatistics()用法及代碼示例
- Node.js http2session.destroyed用法及代碼示例
- Node.js http.ServerResponse response.statusCode用法及代碼示例
- Node.js Buffer buf.writeBigUInt64BE(value[, offset])用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 AsyncLocalStorage。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。