0

の Promise API を中心に Typescript パッケージを構築してamqplib、2 つの RabbitMQ キュー間でメッセージを簡単に送信できるようにしています。

これは、RabbitMQ へのメッセージの送信を担当するパッケージのクラス内のメソッドです。CloudAMQP からメッセージを見ることができないため、実際にはメッセージを送信していません。

class PostOffice {
    connection: any;

    constructor(connection: any) {
        this.connection = connection;
    }

    //...

    // TMQMessage is an object that can be trivially serialized to JSON
    // The Writer class holds the channel because I'm having trouble
    // making Typescript class member updates stick after a method returns.
    async send(writer: Writer, message: TMQMessage) {
        //...RabbitMQ code begins here
        let channel = writer.stageConsume[0]; // This channel is created elsewhere
        
        // Queue is created here and I can see it in CloudAMQP.
        await channel.assertQueue(message.to + "/stage/1", {
            durable: true,
        }); // `message.to` is a string indicating destination, e.g. 'test/hello'
        
        // According to docs, the content should be converted to Buffer
        await channel.sendToQueue(message.to + "/stage/1", Buffer.from(JSON.stringify(message)));
        
        channel.close()
    }

}

これは、ここで使用されている接続とチャネルを作成するために作成したクラスです。

import { Writer } from "./Writer";

export class ConnectionFactory {
    url: string;
    amqp: any;
    constructor(url: string) {
        this.url = url;
        this.amqp = require('amqplib');
    }

    async connect(timeout: number = 2000) {
        let connection = await this.amqp.connect(this.url, {
            // timeout for a message acknowledge.
            timeout, // Make the timeout 2s per now
        })
        return connection;
    }
    async createChannels(connection: any, writer: Writer) {
        //... relevant code starts here
        let stageChannels = [];
        stageChannels.push(await connection.createChannel())
        writer.stageConsume = stageChannels;
        return writer;
    }
}

}

CloudAMQP のダッシュボードから接続を確認できるため、接続ファクトリは正常に動作しているようです。また、作成された (コードでアサートされた) キューもダッシュボードから確認できます。ただし、amqplib から CloudAMQP にメッセージを送信することができません。

パッケージを呼び出すために使用している(非同期)コードは次のとおりです。

let Cf = new ConnectionFactory(url)
let connection = await Cf.connect()
let writer = new Writer();

let message: TMQMessage = {
    //... message content in JSON
}

writer = await Cf.createChannels(connection, writer)
let po = new PostOffice(connection)
await po.send(writer, message)

何が間違っているようですか?

4

1 に答える 1