import { Provide , Scope , ScopeEnum , Init , Config , Destroy , Autoload , } from '@midwayjs/decorator' ; import * as amqp from 'amqp-connection-manager' ; import { Channel , Connection } from 'amqplib' ; import { RabbitmqConfig } from '../../config/config.types' ; @ Autoload ( ) @ Scope ( ScopeEnum . Singleton ) @ Provide ( ) export class RabbitmqService { private channel : Channel ; private connection : Connection ; @ Config ( 'rabbitmq' ) private rabbitmq : RabbitmqConfig ; @ Init ( ) async connect ( ) { this . connection = ( await amqp . connect ( this . rabbitmq . url ) ) as unknown as Connection ; this . channel = await this . connection . createChannel ( ) ; await this . channel . assertQueue ( 'my-queue' , { exclusive : true , autoDelete : true , } ) ; await this . channel . bindQueue ( 'my-queue' , 'my-exchange' , 'create' ) ; return this . connection ; } param queueName param data returns public async sendToQueue ( queueName , data ) { return this . channel . sendToQueue ( queueName , Buffer . from ( data ) , { persistent : true , } ) ; } @ Destroy ( ) async close ( ) { await this . channel . close ( ) ; await this . connection . close ( ) ; } }