一、生产者配置
所在项目为 Producer。
1. 添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置 application.yml
spring:
rabbitmq:
addresses: 121.43.153.00:5672
username: guest
password: guest
virtual-host: /
connection-timeout: 15000
# 启用消息确认模式
publisher-confirm-type: correlated
# 设置return消息模式,注意要和 template.mandatory 一起去配合使用
publisher-returns: true
template:
mandatory: true
3. 发送消息的示例代码:
package com.didiok.component;
import java.util.Map;
import java.util.UUID;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 这里就是确认消息的回调监听接口,用于确认消息是否被 broker 所收到
*/
final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){
/**
* 确认消息后的处理
* @param correlationData 作为消息的唯一标识
* @param ack broker 返回的ack应答
* @param cause 失败时,这里记录失败原因
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.out.println("confirm执行,correlationDataId:"
+ correlationData.getId()
+ ",ack:"
+ ack
+ ", cause:"
+ cause);
}
};
/**
* 对外发送消息的方法
* @param message 消息的具体内容
* @param properties 额外的附加属性
*/
public void send(Object message, Map<String, Object> properties){
MessageHeaders headers = new MessageHeaders(properties);
Message msg = MessageBuilder.createMessage(message, headers);
// 添加confirm机制的回调函数
rabbitTemplate.setConfirmCallback(confirmCallback);
MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
@Override
public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
System.out.println("postProcessMessage:"+message);
return message;
}
};
// 指定业务唯一的id
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().trim());
// 发消息
rabbitTemplate.convertAndSend("exchange-test",
"springboot.producer",
msg,
messagePostProcessor,
correlationData);
}
}
二、消费者
所在项目为 Consumer。
1. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置 application.yml
spring:
rabbitmq:
addresses: 121.43.153.00:5672
username: guest
password: guest
virtual-host: /
connection-timeout: 15000
listener:
simple:
## 表示消费者消费成功消息以后需要手工的进行签收(ack),默认为auto
acknowledge-mode: manual
# 并发数
concurrency: 5
max-concurrency: 10
# broker 在接受到消费者的ack之前允许推送给消费者的消息数量
prefetch: 1
3. 接收消息并消费的示例代码:
package com.didiok.component;
import java.io.IOException;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
@Component
public class Receiver {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 组合使用监听
* @RabbitListener @QueueBinding @Queue @Exchange
* @param message
* @param channel
* @throws IOException
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "queue-test",
durable = "true"),
exchange = @Exchange(
name = "exchange-test",
durable = "true",
type = "topic",
ignoreDeclarationExceptions = "true"),
key = "springboot.*"))
@RabbitHandler
public void onMessage(Message message, Channel channel) throws IOException {
// 1. 收到消息以后进行业务端消费处理
System.out.println("收到消息:" + message.getPayload());
// 2. 处理成功之后 获取deliveryTag 并进行手工的ACK操作, 因为我们配置文件里配置的是 手工签收 spring.rabbitmq.listener.simple.acknowledge-mode=manual
Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
System.out.println(deliveryTag);
channel.basicAck(deliveryTag, false);
}
}
三、测试
在生产者端编写测试代码,也就是在 Producer 项目中编写测试代码。
package com.test;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.imooc.Application;
import com.imooc.component.Sender;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MQTest {
@Autowired
private Sender sender;
@Test
public void sendMessage() throws InterruptedException {
String message = "你好,我是消息,我要来了";
Map<String, Object> properties = new HashMap<>();
properties.put("attr", "附加属性");
properties.put("attr2", "另一个附加属性");
// 发送消息
sender.send(message, properties);
Thread.sleep(10000);
}
}
运行之后,生产者端打印出的信息:
消费者端打印的信息: