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 时,会自动在控制台输出当前生效的分布式锁清单,效果如下:

资源

相关推荐
刘联其1 天前
封装一个完整的HttpClient.ts
前端·javascript·typescript
说给风听.1 天前
解决 Node.js 版本冲突:Windows 系统 nvm 安装与使用全指南
windows·node.js
走粥1 天前
TypeScript 泛型
开发语言·前端·javascript·windows·typescript
森叶1 天前
Node.js 跨进程通信(IPC)深度进阶:从“杀人”的 kill 到真正的信号
node.js·编辑器·vim
阿蒙Amon2 天前
TypeScript学习-第3章:复合类型
javascript·学习·typescript
踢球的打工仔2 天前
typescript-接口的基本使用(三)
前端·javascript·typescript
EndingCoder2 天前
TypeScript 最新特性:跟踪版本更新
开发语言·前端·javascript·typescript
止观止2 天前
重新认识 TypeScript:不仅仅是“带类型的 JS”
javascript·typescript
jiayong232 天前
Vue 3 面试题 - TypeScript 与工程化
前端·vue.js·typescript
虹科网络安全2 天前
艾体宝新闻 | NPM 生态系统陷入困境:自我传播恶意软件在大规模供应链攻击中感染了 187 个软件包
前端·npm·node.js