入门案例
1、增加仓库依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、增加配置文件
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
simple:
# 并发数
concurrency: 5
# 最大并发数
max-concurrency: 10
# 签收模式,auto自动签收,manual手动签收
acknowledge-mode: manual
# 限流 同一时间只能有一条消息过来
prefetch: 1
# 使confirmCallback回调生效
publisher-confirm-type: correlated
# 使returnsCallback回调生效
publisher-returns: true
# 如果配置为false,交换机没有匹配到队列就会丢弃掉消息,而不会触发returnCallback的回调
template:
mandatory: true
3、消费者代码
package com.strap.mydemo.components;
import lombok.extern.log4j.Log4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* <p>消费者</p>
*
* @author strap
*/
@Component
@Log4j
public class MqConsumer {
public MqConsumer() {
}
@RabbitListener(queues = "mq-queue")
public void consume(String msg) {
log.info("消费者已拿到消息:" + msg);
}
}
4、生产者代码
package com.strap.mydemo.components;
import lombok.extern.log4j.Log4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* <p>生产者</p>
*
* @author strap
*/
@Component
@Log4j
public class MqProducer {
private AmqpTemplate rabbitAmqpTemplate;
@Autowired
public MqProducer(AmqpTemplate rabbitAmqpTemplate) {
this.rabbitAmqpTemplate = rabbitAmqpTemplate;
}
public void send(String msg){
// 向消息队列发送消息
// 参数1:队列名称, 参数2:消息
rabbitAmqpTemplate.convertAndSend("mq-queue", msg);
log.info("生产者已发送消息:" + msg);
}
}
6、Demo
package com.strap.mydemo;
import com.strap.mydemo.components.MqProducer;
import lombok.extern.log4j.Log4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* <p></p>
*
* @author strap
*/
@SpringBootTest(args = "--jasypt.encryptor.password=test123")
@Log4j
public class TestMQ {
private MqProducer mqProducer;
@Autowired
public TestMQ(MqProducer mqProducer) {
this.mqProducer = mqProducer;
}
@Test
public void test1() {
mqProducer.send("这是一条通知");
}
}
结果