node-amqp — proper way to handle connection in Express app?

383 Views Asked by At

I'm using Express with node-amqp. My goal is to create amqpConnection and save it to global object before server starts and in Express routes use previously created 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..."

The problem is connection.on "ready"-event is fired eveytime I call a route. I may suppose that's because of Express way of serving http-requests — executing server.js for every route called. So, for every request, a new instance of connection is created and on it's "ready" app tries to create one more instance of Express server.

How to make amqp_connection accessible from any point of my app, but no doubling require("amqp").createConnection() in every point where I need to push something to RabbitMQ?

UPD: or maybe there is no problem with Express. node-amqp seems to fire ready event every second after creation. Don't know if it's correct behavior

Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

Ready event fired multiple 'cause of connection error:

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