线程池
线程池组件 @midwayjs/piscina 基于 Piscina 提供在 Worker 线程池中执行任务的能力,适合 CPU 密集型计算,不会阻塞主线程。
相关信息:
| 描述 | |
|---|---|
| 可用于标准项目 | ✅ |
| 可用于 Serverless | ❌ |
| 可用于一体化 | ✅ |
| 包含独立主框架 | ❌ |
| 包含独立日志 | ❌ |
安装组件
$ npm i @midwayjs/piscina@4 --save
或者在 package.json 中增加如下依赖后,重新安装。
{
"dependencies": {
"@midwayjs/piscina": "^4.0.0"
}
}
引入组件
将组件配置到代码中。
import { Configuration } from '@midwayjs/core';
import * as piscina from '@midwayjs/piscina';
@Configuration({
imports: [
piscina
],
// ...
})
export class MainConfiguration {}
基础用法
框架基于 文档 提供了 PiscinaService 和 PiscinaServiceFactory。
你可以创建单个或者多个线程池对象来管理线程。
以下是 Piscina 的基础用法。
注入 PiscinaService 并调用 run 方法执行任务:
import { Inject, Provide } from '@midwayjs/core';
import * as piscina from '@midwayjs/piscina';
@Provide()
export class UserService {
@Inject()
piscinaService: piscina.PiscinaService;
async heavyTask() {
// 调用 compute 函数
const result1 = await this.piscinaService.run({
handler: 'compute',
payload: { value: 10 },
});
console.log(result1); // 20
// 调用 heavyComputation 函数
const result2 = await this.piscinaService.run({
handler: 'heavyComputation',
payload: { data: [1, 2, 3, 4, 5] },
});
console.log(result2); // 15
}
}