完整配置参考
本页是 new MonSQLize(options) 的公开配置参考,只说明构造函数配置。find(..., { cache, maxTimeMS }) 这类方法级选项放在对应 API 文档中说明。
当你需要确认下面这些问题时,优先看本页:
- 最小可用配置怎么写?
- 哪些字段可以全局配置?
- MongoDB、缓存、Redis、Model、同步、连接池、日志、分页应该如何组合?
- 哪些是默认值,哪些会在运行时校验?
最小配置
import MonSQLize from 'monsqlize';
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'app',
config: {
uri: 'mongodb://127.0.0.1:27017'
}
});
await msq.connect();
const users = msq.collection('users');
const list = await users.find({ status: 'active' }).toArray();
await msq.close();
当前 runtime 要求显式传入 type: 'mongodb'。databaseName 建议显式配置;如果省略,runtime 会按 database、databaseName、default 的顺序解析默认数据库名。
生产配置示例
import MonSQLize from 'monsqlize';
const redisUrl = 'redis://127.0.0.1:6379/0';
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: {
uri: 'mongodb://mongo.internal:27017/shop',
options: {
maxPoolSize: 20,
minPoolSize: 2,
serverSelectionTimeoutMS: 5000
}
},
maxTimeMS: 3000,
findLimit: 500,
findMaxLimit: 10000,
findMaxSkip: 50000,
findPageMaxLimit: 500,
slowQueryMs: 500,
cursorSecret: 'replace-with-a-stable-secret',
requireCursorSecret: true,
cache: {
memory: {
maxEntries: 100000,
defaultTtl: 60000,
enableStats: true
},
redis: {
url: redisUrl,
timeoutMs: 300,
prefix: 'shop:'
},
distributed: {
redisUrl,
channel: 'shop:cache:invalidate',
instanceId: 'api-1'
}
},
cacheAutoInvalidate: true,
logger: console,
slowQueryLog: {
enabled: true,
storage: {
type: 'mongodb',
useBusinessConnection: true,
database: 'ops',
collection: 'slow_queries',
ttl: 7 * 24 * 3600
}
},
models: {
path: './models',
pattern: '*.model.{js,mjs,cjs}',
recursive: false
},
autoIndex: false,
writePathPolicy: {
default: 'allow-both'
}
});
Redis 二级缓存和分布式失效可以共用同一个 Redis URL。二者职责不同:二级缓存存储查询结果,cache.distributed 使用 Pub/Sub 做跨实例失效广播。
顶层配置项
Mongo 连接配置
config 会传给 MongoDB adapter,并参与可选 SSH / memory-server 初始化。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'private_app',
config: {
uri: 'mongodb://mongo.internal:27017/private_app',
ssh: {
host: 'bastion.example.com',
port: 22,
username: 'deploy',
privateKeyPath: '~/.ssh/id_rsa'
},
remoteHost: 'mongo.internal',
remotePort: 27017
}
});
缓存配置
查询缓存是按查询启用的。全局 cache 只决定“某个查询要求缓存时,缓存结果存在哪里”。
在单次查询上使用 cache: 0 可禁用该查询缓存。构造函数层面如需禁用 cache backend,使用 cache: { enabled: false }。不要把 boolean 作为构造函数 cache 配置传入。
内存缓存
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
cache: {
maxEntries: 100000,
maxMemory: 0,
defaultTtl: 60000,
enableStats: true,
enableTags: false,
cleanupInterval: 60000
}
});
Redis 二级缓存
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
cache: MonSQLize.createRedisCacheAdapter('redis://127.0.0.1:6379/0')
});
本地 + Redis 双层缓存推荐使用 memory + redis 声明式写法:
const redisUrl = 'redis://127.0.0.1:6379/0';
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
cache: {
memory: { maxEntries: 10000, defaultTtl: 60000 },
redis: { url: redisUrl, timeoutMs: 300, prefix: 'shop:' },
policy: {
writePolicy: 'both',
backfillLocalOnRemoteHit: true
}
}
});
分布式缓存失效
cache.distributed 开启 Redis Pub/Sub 失效广播。runtime 不会自动从 cache.remote 推断 Pub/Sub 连接;需要显式配置 redisUrl、url、uri 或已有 Redis-like redis 实例。
const redisUrl = 'redis://127.0.0.1:6379/0';
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
cache: {
memory: { maxEntries: 10000 },
redis: { url: redisUrl },
distributed: {
redisUrl,
channel: 'shop:cache:invalidate',
instanceId: 'api-1',
enabled: true
}
}
});
缓存失效是 best-effort,跨实例最终收敛。MongoDB 写入成功后,如果后续缓存失效或分布式广播失败,runtime 不会回滚数据库写入。
Logger 配置
可以传 console、null,或暴露四个日志方法的对象。{ level: 'debug' } 这类对象不会生效,因为它不满足 logger 接口。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
logger: {
debug: (...args) => console.debug(...args),
info: (...args) => console.info(...args),
warn: (...args) => console.warn(...args),
error: (...args) => console.error(...args)
}
});
Model 与 schema-dsl 配置
Model 层默认使用隔离的 schema-dsl/runtime。只有在需要注入已有 runtime、注册扩展、传入 runtime options 或显式关闭 schema-dsl 校验时,才需要配置 schemaDsl。
import { createRuntime } from 'schema-dsl/runtime';
const schemaRuntime = createRuntime({
messages: {
required: 'Required field'
}
});
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
schemaDsl: {
runtime: schemaRuntime
}
});
写路径策略
默认情况下,collection 与 Model 写入都可用。如果某些命名空间必须经过 Model hooks、默认值、时间戳、版本与软删除规则,可以配置 model-only。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
writePathPolicy: {
default: 'model-only',
namespaces: {
'shop.audit_logs': 'allow-both'
}
}
});
详见 写路径策略。
连接池配置
当服务需要具名数据库连接时,在构造函数中配置 pools。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'main',
config: { uri: 'mongodb://primary:27017/main' },
pools: [
{
name: 'analytics',
uri: 'mongodb://analytics:27017/main',
role: 'analytics',
tags: ['reporting'],
options: { maxPoolSize: 5 }
}
],
poolStrategy: 'auto',
poolFallback: { enabled: true, fallbackStrategy: 'primary' },
maxPoolsCount: 5
});
const reports = msq.pool('analytics').collection('reports');
详见 连接池配置。
同步配置
sync 会接入 Change Stream fan-out manager。runtime 提供 at-least-once 语义,target 应保持幂等。可以用 sync.idempotency 减少重复 target 副作用。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'main',
config: { uri: 'mongodb://primary:27017/main?replicaSet=rs0' },
sync: {
enabled: true,
collections: ['orders'],
targets: [
{
name: 'backup',
uri: 'mongodb://backup:27017',
databaseName: 'backup',
collections: ['orders']
}
],
resumeToken: {
storage: 'file',
path: './.sync-resume-token',
strictLoad: true,
strictSave: true,
saveRetries: 2,
saveRetryDelayMs: 100
},
idempotency: {
enabled: true,
keyPrefix: 'monsqlize:sync:idempotency',
ttl: 24 * 3600 * 1000,
markMode: 'success'
}
}
});
详见 Change Stream 同步。
慢查询日志
slowQueryMs 控制 runtime 阈值;需要持久化聚合慢查询记录时配置 slowQueryLog。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
slowQueryMs: 500,
log: {
slowQueryTag: { event: 'slow_query', code: 'SLOW_QUERY' },
formatSlowQuery: (meta) => meta
},
slowQueryLog: {
enabled: true,
storage: {
type: 'mongodb',
useBusinessConnection: true,
database: 'ops',
collection: 'slow_queries',
ttl: 7 * 24 * 3600
},
filter: {
minExecutionTimeMs: 1000,
excludeCollections: ['healthchecks']
}
}
});
详见 慢查询日志。
事务配置
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017/shop?replicaSet=rs0' },
transaction: {
enableRetry: true,
maxRetries: 3,
retryDelay: 100,
retryBackoff: 2,
defaultTimeout: 30000,
lockMaxDuration: 30000,
lockCleanupInterval: 60000
}
});
事务缓存锁是进程内锁。跨实例关键流程应使用应用层幂等/fencing 或显式业务锁。
运行时校验
以下构造项会在实例创建时校验:
findLimit 还必须小于或等于 findMaxLimit。
配置优先级
同一能力同时存在实例级与方法级配置时,方法级配置优先。
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'shop',
config: { uri: 'mongodb://127.0.0.1:27017' },
maxTimeMS: 3000
});
await msq.connect();
const users = msq.collection('users');
await users.find({}, { maxTimeMS: 5000 }); // 使用 5000。
await users.find({}); // 使用 3000。
常见误区
相关文档