概念介紹
這里引用rabbit官網(wǎng)的一張圖
image.png
大概意思就是生產(chǎn)者把消息發(fā)送到隊(duì)列然后消費(fèi)者消費(fèi)消息
springboot實(shí)現(xiàn)
hello-world比較簡單這里直接上代碼
生產(chǎn)者
聲明默認(rèn)配置
@Component
@Data
public class MyBean {
private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate;
@Autowired
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
}
//聲明一個(gè)隊(duì)列springboot會(huì)自動(dòng)綁定到默認(rèn)的路由
@Bean
Queue queue(){
return QueueBuilder.durable("hello").build();
}
}
發(fā)送消息
@Autowired
MyBean myBean;
//注意這里默認(rèn)的routingkey為隊(duì)列的名稱,請和上面聲明的隊(duì)列保持一致
@Test
void msgSend(){
myBean.getAmqpTemplate().convertAndSend("hello","hello-world!");
}
感覺比不用springboot少了一大堆代碼有沒有...太簡潔了
消費(fèi)者
消費(fèi)者就更簡單了直接一句話
@Component
@Slf4j
public class ReceiverBean {
@RabbitListener(queues = "hello")
public void processMessage(String msg) {
log.info("msg---"+msg);
}
}
這里貼springboot手冊關(guān)于rabbitmq的一段話
image.png
大概意思就是如果沒有特殊的配置springboot會(huì)啟用默認(rèn)的工廠骚烧,接收消息直接用這個(gè)就可以了
其他
另外大家是不是發(fā)現(xiàn)我沒有配置rabbit的用戶名密碼谆趾,如果是本機(jī)如果你用的是默認(rèn)的用戶名密碼是不需要寫的(guest:guest)
最后上代碼
消費(fèi)者/生產(chǎn)者
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-helloworld-consumer
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-helloworld-producer