0

我将 Express 与 node-amqp 一起使用。我的目标是在服务器启动之前创建 amqpConnection 并将其保存到全局对象中,并且在 Express 路由中使用之前创建globals.amqp_connection的 .

### server.coffee

app.use( ... )
...

# create RabbitMQ connection before server starts
connection = require("amqp").createConnection
  host: "localhost"

connection.on "ready", ->

  console.log "Got connection.on(\"ready\") event from node-amqp..."

  # make amqp_connection accessible from any point of application
  globals.amqp_connection = connection

  server = globals.http.createServer(app).listen(8082)

  console.log "Express server is listening 8082..."

问题是connection.on "ready"-event 每次我调用路由时都会触发。我可能认为这是因为 Express 服务 http-requests 的方式——为每个调用的路由执行 server.js。因此,对于每个请求,都会创建一个新的实例,connection并在其上“准备好”的应用程序尝试再创建一个 Express 服务器实例。

如何使 amqp_connection 可以从我的应用程序的任何点访问,但require("amqp").createConnection()在我需要将某些东西推送到 RabbitMQ 的每个点都没有加倍?

UPD:或者Express没有问题。node-amqp 似乎在创建后每秒触发一次就绪事件。不知道这是否是正确的行为

谢谢你。

4

1 回答 1

0

就绪事件触发了多个“连接错误的原因:

https://github.com/postwait/node-amqp/issues/255

于 2014-12-18T09:50:23.997 回答