帮我使用版本2的eggJS框架实现rabbitmq的生产者与消费者
时间: 2024-05-14 16:18:43 浏览: 201
好的,以下是使用 EggJS 框架实现 RabbitMQ 生产者与消费者的示例代码:
1. 安装 amqplib
```
npm install amqplib
```
2. 配置 RabbitMQ
在 `config/config.default.js` 文件中添加 RabbitMQ 的配置信息:
```javascript
config.rabbitmq = {
username: 'your-username',
password: 'your-password',
host: 'your-host',
port: 'your-port',
};
```
3. 编写生产者代码
在 `app/service` 目录下创建 `producer.js` 文件,编写生产者代码:
```javascript
const amqp = require('amqplib');
class ProducerService {
async produce(message) {
const connection = await amqp.connect(`amqp://${this.config.rabbitmq.username}:${this.config.rabbitmq.password}@${this.config.rabbitmq.host}:${this.config.rabbitmq.port}`);
const channel = await connection.createChannel();
const queue = 'your-queue-name';
await channel.assertQueue(queue, { durable: true });
channel.sendToQueue(queue, Buffer.from(message), { persistent: true });
console.log(`Sent message: ${message}`);
await channel.close();
await connection.close();
}
}
module.exports = ProducerService;
```
4. 编写消费者代码
在 `app/service` 目录下创建 `consumer.js` 文件,编写消费者代码:
```javascript
const amqp = require('amqplib');
class ConsumerService {
async consume() {
const connection = await amqp.connect(`amqp://${this.config.rabbitmq.username}:${this.config.rabbitmq.password}@${this.config.rabbitmq.host}:${this.config.rabbitmq.port}`);
const channel = await connection.createChannel();
const queue = 'your-queue-name';
await channel.assertQueue(queue, { durable: true });
channel.consume(queue, (message) => {
console.log(`Received message: ${message.content.toString()}`);
channel.ack(message);
}, { noAck: false });
}
}
module.exports = ConsumerService;
```
5. 在控制器中调用生产者
在需要发送消息的控制器中调用生产者:
```javascript
const Controller = require('egg').Controller;
class MessageController extends Controller {
async send() {
const { ctx } = this;
const message = ctx.request.body.message;
await ctx.service.producer.produce(message);
ctx.body = 'Message sent';
}
}
module.exports = MessageController;
```
6. 在应用启动时启动消费者
在 `app.js` 文件中启动消费者:
```javascript
const ConsumerService = require('./app/service/consumer');
class AppBootHook {
constructor(app) {
this.app = app;
}
async didReady() {
const consumerService = new ConsumerService(this.app);
await consumerService.consume();
}
}
module.exports = AppBootHook;
```
这样就完成了使用 EggJS 框架实现 RabbitMQ 生产者与消费者的代码。
阅读全文