Skip to content
This repository has been archived by the owner on Jul 5, 2022. It is now read-only.

hackycy/midway-bull

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

midway-bull (Deprecated)

请使用官方包代替:@midwayjs/task@3

NPM version npm download

bull component for MidwayJs.

安装

$ npm i --save midway-bull
$ npm i --save-dev @types/bull

使用方法

configuration.ts导入子组件

import * as bull from 'midway-bull';

@Configuration({
  imports: [bull],
})
export class ContainerLifeCycle implements ILifeCycle {}

配置

config.${env}.ts中配置对应信息,与代码配置队列名一一对应

export const bull = {
  SysTask: {
    redis: {
      port: 6379,
      host: '127.0.0.1',
      password: '123456',
      db: 0,
    },
    prefix: 'admin:task',
  },
};

代码编写

定义队列

import { IMidwayWebApplication } from '@midwayjs/web';
import { IQueue, Queue } from 'midway-bull';
import { App, Provide } from '@midwayjs/decorator';

/**
 * 第一个参数对应配置文件中的key,支持string或者直接为QueueOptions配置对象
 * 第二参数为需要监听队列触发的event事件,该项不注册则不会回调onEvent
 */
@Queue('SysTask', ['completed'])
@Provide()
export class SysTaskQueue implements IQueue {
  @App()
  app: IMidwayWebApplication;

  async excute(data: any): Promise<void> {
    // exec something
  }

  onEvent(e: string, ...args: any[]): void {
    // on event
  }
}

获取队列

import { App, Inject, Provide } from '@midwayjs/decorator';
import { BullService } from 'midway-bull';
import { SysTaskQueue } from './sys-task'

@Provide()
export class AdminSysTaskService extends BaseService {
  @Inject('bull:bullService')
  bullService: BullService;

  @App()
  app: IMidwayApplication;

  async addTask() {
    // 3秒后触发分布式任务调度。
    await this.bullService.excute(SysTaskQueue, { name: '' }, { delay: 3000 })
  }

  async getQueue() {
    return this.bullService.getQueue(SysTaskQueue)
  }
}