安装比较简单,直接使用 brew 就可以;
brew update
brew install rabbitmq
brew install rabbitmq
如果 brew 是国外的源, 可能安装很慢, 可以更改为国内的源
打开终端执行:/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
该地址提供多个国内源地址
安装成功后, 使用
rabbitmq-server start
命令进行启动
启动后, 可使用网页端进行查看队列
默认的登陆账号密码为: guest
下面是一个简单的使用 demo, 使用 nodejs 实现:
需要先安装: npm i amqplib
生产端:每隔 500ms 推送一条消息
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import * as amqp from 'amqplib' const connect = await amqp.connect(`amqp://localhost:5672`); const channel = await connect.createChannel(); await channel.assertQueue('aaa', { durable: false }); let i = 1; setInterval(async () => { const msg = 'hello' + i; console.log('发送消息:', msg); await channel.sendToQueue('aaa',Buffer.from(msg)) i++; }, 500); |
消费端: 每间隔 3 秒读取一条消息;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import * as amqp from 'amqplib' const sleep = (time) => { return new Promise(resolve => { setTimeout(_ => resolve(), time * 1000) }) } const x = async () => { const connect = await amqp.connect(`amqp://localhost:5672`); const channel = await connect.createChannel(); const {queue} = await channel.assertQueue('aaa', {durable: false}); // 一次性读取一条; channel.prefetch(1); channel.consume(queue, async (msg) => { if (msg !== null) { console.log('收到数据', msg?.content?.toString()); await sleep(3); channel.ack(msg); } }); } await x() |
修改 channel.prefetch(3); 可设置读取条数。
这就是简单的 amqplib 消息队列使用方法;