VonaJS: 直观好用的分布式锁

分布式锁

VonaJS 基于Redlock提供了直观、易用的分布式锁

创建分布式锁

比如,在模块 demo-student 中创建分布式锁

1. Cli命令

bash 复制代码
$ vona :create:bean meta redlock --module=demo-student

2. 菜单命令

bash 复制代码
右键菜单 - [模块路径]: `Vona Meta/Redlock`

分布式锁定义

typescript 复制代码
export type TypeRedlockLockResource = never;
export type TypeRedlockLockIsolateResource = never;

@Meta()
export class MetaRedlock extends BeanRedlockBase<TypeRedlockLockResource, TypeRedlockLockIsolateResource> {}
  • TypeRedlockLockResource: 定义lock方法使用的锁资源
  • TypeRedlockLockIsolateResource: 定义lockIsolate方法使用的锁资源

定义锁资源

当我们使用分布式锁时,需要指定对应的锁资源。比如,为lock方法定义锁资源name:

diff 复制代码
- export type TypeRedlockLockResource = never;
+ export type TypeRedlockLockResource = 'name';

使用分布式锁

typescript 复制代码
class ControllerStudent {
  async test() {
    const res = await this.scope.redlock.lock('name', async () => {
      // do something in lock
      return 'some result';
    });
  }
}  
  • redlock.lock:传入锁资源name

lock/lockIsolate

VonaJS 提供了两个锁方法: lock/lockIsolate。二者的区别是:lockIsolate自动实现了数据源分级,从而避免因数据源竞争而导致的死锁情况

定义锁资源: lockIsolate

lockIsolate方法定义锁资源:

diff 复制代码
- export type TypeRedlockLockIsolateResource = never;
+ export type TypeRedlockLockIsolateResource = 'name';

使用分布式锁: lockIsolate

typescript 复制代码
class ControllerStudent {
  async test() {
    const res = await this.scope.redlock.lockIsolate('name', async () => {
      // do something in lock
      return 'some result';
    });
  }
}  

定义锁资源: 字面量模版

锁资源还可以是字面量模版

比如,如果要为不同的用户单独提供锁资源,那么可以使用形如user-${userId}的字符串,作为锁资源名称

diff 复制代码
- export type TypeRedlockLockIsolateResource = 'name';
+ export type TypeRedlockLockIsolateResource = 'name' | `user-${string}`;

这样,在使用lockIsolate方法时同样可以提供类型提示

typescript 复制代码
class ControllerStudent {
  async test() {
    const userId = 1;
    const res = await this.scope.redlock.lockIsolate(`user-${userId}`, async () => {
      // do something in lock
      return 'some result';
    });
  }
}  

查看当前生效的分布式锁清单

可以直接输出当前生效的分布式锁清单

diff 复制代码
class ControllerStudent {
  @Web.get('test')
  test() {
+   this.bean.onion.meta.inspectMeta('redlock');
  }
}
  • this.bean.onion: 取得全局 Service 实例 onion
  • .meta: 取得与 meta 相关的 Service 实例
  • .inspectMeta: 输出当前生效的分布式锁清单

当访问test API 时,会自动在控制台输出当前生效的分布式锁清单,效果如下:

资源

相关推荐
codingWhat13 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
Wect14 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
ServBay14 小时前
Node.js、Bun 与 Deno,2026 年后端运行时选择指南
node.js·deno·bun
mCell17 小时前
从零构建一个 Mini Claude Code:面向初学者的 Agent 开发实战指南
typescript·agent·claude
敲敲敲敲暴你脑袋20 小时前
写个添加注释的vscode插件
javascript·typescript·visual studio code
码路飞21 小时前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
Wect21 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
昨晚我输给了一辆AE862 天前
为什么现在不推荐使用 React.FC 了?
前端·react.js·typescript
None3212 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Wect2 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript