传递 Javascript amqplib 通道以在 ExpressJS 中路由中间件

Passing Javascript amqplib Channel To Route Middleware In ExpressJS

我正在尝试在我的快速服务器启动时创建一个 amqplib 连接/通道,并将其传递给路由,以便它们可以声明队列、发布消息等。我尝试过中间件,但每次你去路由并调用中间件,建立一个新的连接。

我将我的路由中间件从我的 index.js 文件中分离出来,所以保持整洁,这样我就不能只在 index.js.

中定义 amqp 队列/发布逻辑

例如...

// index.js
// ...
const amqplibConnection = // create amqp connection;
const channel = amqplibConnection.createChannel();

const app = express();
const fooRoutes = require('./routes/foo')
// how can I pass channel to ./routes/foo ???
app.use('/api/v1/foo', fooRoutes);

// routes/foo.js
const router = express.Router();
router.get('/', (req, res) => {
    // declare queue, publish message, etc ...
});

您可以在以下代码中找到 mark1。
mark1:创建新的中间件并将通道分配给 req.channel 然后调用 next(),您可以在 foo.js.

中使用 req.channel
// index.js
// ...
const amqplibConnection = // create amqp connection;
const channel = amqplibConnection.createChannel();

const app = express();
const fooRoutes = require('./routes/foo')
// ================= mark1 =================
app.use('/api/v1/foo', (req, res, next) => {
    req.channel = channel;
    next();
}, fooRoutes);

// routes/foo.js
const router = express.Router();
router.get('/', (req, res) => {
    // declare queue, publish message, etc ...
    req.channel... // do something
});