NodeJS CLS
约 1 分钟阅读
- Continuation Local Storage - 连续本地存储
- AsyncLocalStorage - node v12.17+
- 类似 ThreadLocal
- getStore, setStore
- disable
- enterWith - 当前环境 - AsyncResource 上下文
- run - callback 内生效
- exit - callback 内失效
- AsyncLocalStorage.snapshot
- AsyncResource
// 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()}`);
});
});- async_hooksGitHub Filenodejs/node/doc/api/async_hooks.md - node v8+
- currentId()
- triggerAsyncId()
- executionAsyncId()
- nodejs.org/api/async_context.html
// node 8+
import { createHook } from 'async_hooks';
const hook = createHook({
init: (asyncId, type, triggerId, resource) => {},
before: (asyncId) => {},
after: (asyncId) => {},
destroy: (asyncId) => {},
});
hook.enable();- @fastify/request-contextGitHubfastify/fastify-request-context
- asynchronous-local-storage
- async_hooks
new AsyncResource('fastify-request-context')
- onRequest - 包装运行环境
- als.runWith
- AsyncResource.runInAsyncScope(done,req,raw)
- als.runWith
const { als } = require('asynchronous-local-storage');
const requestContext = {
get: als.get,
set: als.set,
};- sequelize.org/docs/v7/other-topics/transactions
const namespace = cls.createNamespace('sequelize-tx');- useCLSGitHub Filesequelize/sequelize/src/sequelize.js#L1147-L1158
- get, set, bind, run
bind(fn,context): ()=>any
- prepareEnvironment
- 开启事务
this.sequelize.Sequelize._cls.set('transaction', this);
- asynchronous-local-storageGitHubkibertoad/asynchronous-local-storage
- Node.js ALS with fallback to cls-hooked
- cls-hookedGitHubJeff-Lewis/cls-hooked
- node 4.7+ - async-hook-jl
- node 8+ - async_hooks
- fork 自 continuation-local-storage
- continuation-local-storageGitHubothiym23/node-continuation-local-storage
const cls = require('cls-hooked');
const namespace = cls.createNamespace('my-very-own-namespace');关联信息
反向链接、本文链接的其他页面和外部资料。
References
GitHub6 条
- fastify/fastify-request-contextgithub.com/fastify/fastify-request-context
- Jeff-Lewis/cls-hookedgithub.com/Jeff-Lewis/cls-hooked
- kibertoad/asynchronous-local-storagegithub.com/kibertoad/asynchronous-local-storage
- nodejs/node/doc/api/async_hooks.mdgithub.com/nodejs/node/blob/main/doc/api/async_hooks.md
- othiym23/node-continuation-local-storagegithub.com/othiym23/node-continuation-local-storage
- sequelize/sequelize/src/sequelize.js#L1147-L1158github.com/sequelize/sequelize/blob/fdd713172748a6c86b656500df2aed8cba096492/src/sequelize.js
其他外链2 条
- nodejs.org/api/async_context.htmlnodejs.org/api/async_context.html
- sequelize.org/docs/v7/other-topics/transactionssequelize.org/docs/v7/other-topics/transactions