Wener Notes

NodeJS CLS

约 1 分钟阅读
  • Continuation Local Storage - 连续本地存储
  • AsyncLocalStorage - node v12.17+
    • 类似 ThreadLocal
    • getStore, setStore
    • disable
    • enterWith - 当前环境 - AsyncResource 上下文
    • run - callback 内生效
    • exit - callback 内失效
    • AsyncLocalStorage.snapshot
  • AsyncResource
TypeScript
// ALS
// v13.10.0, v12.17.0
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
asyncLocalStorage.run(123, () => {
  console.log(`Store: ${asyncLocalStorage.getStore()}`);
  setImmediate(() => {
    console.log(`setImmediate Store: ${asyncLocalStorage.getStore()}`);
  });
});
TypeScript
// node 8+
import { createHook } from 'async_hooks';
const hook = createHook({
  init: (asyncId, type, triggerId, resource) => {},
  before: (asyncId) => {},
  after: (asyncId) => {},
  destroy: (asyncId) => {},
});
hook.enable();
TypeScript
const { als } = require('asynchronous-local-storage');
const requestContext = {
  get: als.get,
  set: als.set,
};
TypeScript
const cls = require('cls-hooked');
const namespace = cls.createNamespace('my-very-own-namespace');

关联信息

反向链接、本文链接的其他页面和外部资料。

References

GitHub6 条
其他外链2 条
最近更新commit f8c52f1Edit

On this page