SpringBoot使用RabbitMQ
首先在SpringBoot上使用RabbitMQ需要引入spring-boot-starter-amqp的依赖,消费者和生产者都需要。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alnk</groupId>
<artifactId>rabbitmq-springboot-consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
RabbitMQ 的Consumer端代码
1、配置文件application.properties如下
server.port=8082
#rabbitmq地址
spring.rabbitmq.addresses=192.168.1.221:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=20000
#表示消费者接受消息后需要手动进行签收ack,默认auto自动
spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.concurrency=5
spring.rabbitmq.listener.simple.max-concurrency=10
spring.rabbitmq.listener.simple.prefetch=1
2、消费者端代码如下
@Component
@Slf4j
public class RabbitReceiver {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue-springboot",declare = "true"),
exchange = @Exchange(name = "exchange-springboot",type = "topic",declare = "true"),
key = "springboot.*"
))
@RabbitHandler
public void onMessage(Message message, Channel channel) throws IOException {
log.error("--------------------");
//获取消息体
log.info("message:{}",message.getPayload());
//消息消费ack
Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
log.info("headers:{}",message.getHeaders());
channel.basicAck(deliveryTag,false);
}
}
RabbitMQ 的Producer端代码
1、消息发送者application.properties
server.port=8081
spring.rabbitmq.addresses=192.168.1.221:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=20000
#开始确认消息
spring.rabbitmq.publisher-confirm-type=correlated
#设置return消息,需要和mandatory一起使用
#spring.rabbitmq.publisher-returns=true
#spring.rabbitmq.template.mandatory=true
2、消息发送者service代码,因为开启了确认消息,所以需要实现ConfirmCallback接口。通过里面的ack可以判断发送是否成功。代码如下:
@Component
@Slf4j
public class RabbitSender {
@Autowired
private RabbitTemplate rabbitTemplate;
final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
/**
* 确认消息回调监听方法
* @param correlationData 作为消息的唯一标识
* @param ack 是否落盘成功
* @param cause 失败原因
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
log.info("correlationData:{},ack:{},cause:{}",correlationData,ack,cause);
}
};
/**
* 消息发送前对消息的操作
*/
final MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
@Override
public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
log.info("messagePostProcessor:{}",message);
return message;
}
};
/**
* 发送消息的方法
* @param message 消息对象
* @param properties 消息的配置,如过期时间
*/
public void send(Object message, Map<String,Object> properties){
MessageHeaders messageHeaders = new MessageHeaders(properties);
Message<Object> msg = MessageBuilder.createMessage(message, messageHeaders);
//确认消息设置回调
rabbitTemplate.setConfirmCallback(confirmCallback);
//生产发送该条消息唯一标识
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
rabbitTemplate.convertAndSend("exchange-springboot","springboot.rabbit",msg,messagePostProcessor,correlationData);
}
}
写一个Controller对项目进行测试:
@RestController
public class TestController {
@Autowired
private RabbitSender rabbitSender;
@RequestMapping("send")
public String testRabbit(String msg){
Map<String,Object> prop = new HashMap<>();
prop.put("lank",123);
rabbitSender.send(msg,prop);
return "消息发送成功";
}
}
调用http://localhost:8081/send?msg=hello后可以看到consumer控制台把日志信息都打印出来了
源码地址:https://github.com/lank-java/mq/tree/main/rabbitmq