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

资源

相关推荐
张雨zy17 小时前
Pinia 与 TypeScript 完美搭配:Vue 应用状态管理新选择
vue.js·ubuntu·typescript
Kagol1 天前
🎉TinyVue v3.27.0 正式发布:增加 Space 新组件,ColorPicker 组件支持线性渐变
前端·vue.js·typescript
Drift_Dream1 天前
Node.js第一课:实现简易的命令行任务管理器
node.js
user297525876121 天前
AI实践:结合LangChain实现一个自动生成项目README的VSCode插件
langchain·node.js·visual studio code
若梦plus1 天前
Node.js之TypeScript支持
前端·typescript
若梦plus1 天前
Node.js基础与常用模块
前端·node.js
若梦plus1 天前
Node.js之进程管理child_process与cluster深度解析
前端·node.js
若梦plus1 天前
Node.js之核心模块
前端·node.js
LoveDreaMing1 天前
MCP入门梳理
前端·typescript·mcp
风舞红枫1 天前
node代理vue打包后的文件,实现本地测试
前端·javascript·vue.js·node.js