node-amqp で Express を使用しています。私の目標は、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"
、ルートを呼び出すたびにイベントが発生することです。これは、HTTP 要求を処理する Express の方法 (呼び出されるすべてのルートに対して server.js を実行する) が原因であると考えられます。そのため、リクエストごとに の新しいインスタンスconnection
が作成され、その「準備が整った」アプリで、Express サーバーのインスタンスをもう 1 つ作成しようとします。
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.