amqplib未连接到本地主机RabbitMQ

t3irkdon  于 2022-11-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(162)

关于这个问题,我经历了几个SO线程。没有任何效果。但是我的情况不同。在我的情况下,什么也没有发生。下面是代码:

import amqplib from 'amqplib'

const AMQP_URL = 'amqp://guest:guest@localhost:5672/'
const AMQP_QUEUE_NAME = 'email_queue'

function connectRabbitMQ() {
    console.log('Connecting to rabbit mq...')
    amqplib.connect(AMQP_URL, async (err: Error, connection: amqplib.Connection) => {
        if (err) {
            console.log('This log doesn\'t print')
            throw err
        }
        console.log('This log doesn\'t print')

        // Listener
        const channel1 = await connection.createChannel()
        channel1.consume(AMQP_QUEUE_NAME, (msg) => {
            if (msg !== null) {
                console.log('Recieved:', msg.content.toString());
                channel1.ack(msg);
            } else {
                console.log('Consumer cancelled by server');
            }
        })

        // Sender
        const channel2 = await connection.createChannel()
        setInterval(() => {
            channel2.sendToQueue(AMQP_QUEUE_NAME, Buffer.from('something'))
        }, 1000)
    })
}

function launchServer() {
    console.log('Launching Server...')
    console.log('Connecting to MongoDB...')
    const MONGODB_URI = process.env.MONGODB_URI?.toString() || ''
    mongoose.connect(MONGODB_URI, {}, (err) => {
        if (err) {
            return console.error('Error connecting to Mongo DB !')
        }
        console.log('CONNECTED TO MONGO DB')
        const port = parseInt(process.env.PORT?.toString() || '3000')
        app.listen(port)
        console.log('========= SERVER STARTED ========== PORT ' + port)
        connectRabbitMQ()
    })
}
launchServer()

未发生错误或成功。未打印日志。最后打印的日志为-Connecting to rabbit mq...

uubf1zoe

uubf1zoe1#

函数connectRabbitMQ似乎没有被执行。尝试将此附加到代码的最后一行

connectRabbitMQ();

相关问题