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

资源

相关推荐
濮水大叔2 小时前
VonaJS: I18n如何支持Swagger多语言
typescript·node.js·nestjs
孟陬3 小时前
Bun Test 不支持时间快进?我用这招让单元测试提速 8 倍!
node.js·测试·bun
Less^_^5 小时前
使用 Node.js 开发 Telegram Bot 完整指南
ai·node.js
小飞大王66611 小时前
TypeScript核心类型系统完全指南
前端·javascript·typescript
防火墙在线13 小时前
前后端通信加解密(Web Crypto API )
前端·vue.js·网络协议·node.js·express
键盘飞行员15 小时前
Vue3+TypeScript项目中配置自动导入功能,遇到了问题需要详细的配置教程!
前端·typescript·vue
水冗水孚18 小时前
效能工具(九)之编写nodejs脚本使用get-video-duration批量读取视频时长,并生成sql语句修复数据库表字段值
sql·node.js
来碗盐焗星球18 小时前
简单聊下enum(枚举)
typescript