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

资源

相关推荐
by__csdn2 小时前
Vue2纯前端图形验证码实现详解+源码
前端·javascript·typescript·vue·状态模式·css3·canva可画
我是阿亮啊2 小时前
搭建Vue环境遇到的问题
javascript·vue.js·npm·node.js
0***h9423 小时前
Windows 11 如何配置node.js
windows·node.js
Dr_哈哈7 小时前
LangChain Tools —— 让 AI 拥有「双手」
langchain·node.js·ai编程
Dr_哈哈7 小时前
LangChain Chain & Pipe 知识点详解
langchain·node.js·ai编程
j***29488 小时前
如何在Windows系统上安装和配置Node.js及Node版本管理器(nvm)
windows·node.js
进击的野人8 小时前
Node.js文件系统(fs模块)深度解析与实践应用
后端·正则表达式·node.js
z***3359 小时前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
悟能不能悟10 小时前
在TypeScript中 const xxx=(xx:any)=>{}为什么要加any
linux·git·typescript
2***656311 小时前
windows下安装并使用node.js
windows·node.js