前面章节学习都是基于spring,配置麻烦,现在生产中也没人那么使用,下面讲解基于springboot来操作MQ
代码地址:https://gitee.com/webprogram/springboot_rabbit
SpringBoot整合RabbitMQ
引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
配置
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: admin
password: admin
virtual-host: my_vhost
publisher-confirm-type: correlated #开启交换机应答
publisher-returns: true #开启队列应答
template:
mandatory: true #开启强制消息投递
listener:
simple:
acknowledge-mode: manual #手动应答
concurrency: 1 #当前监听容器数
max-concurrency: 1 #当前监听最大容器数
retry:
enabled: true #开启重试
注册交换机、队列
@Configuration
public class RabbitConfig {
// 定义交换机,类型TOPIC
@Bean
public Exchange topicExchange() {
return ExchangeBuilder.topicExchange("topic_exchange").build();
}
// 定义队列,nonDurable不支持持久化的
@Bean
public Queue topicQueue() {
return QueueBuilder.nonDurable("topic_queue").build();
}
// 绑定交换机和队列,实际生产为了灵活采用rabbit控制台进行操作绑定
@Bean
public Binding topicBinding(@Qualifier("topicQueue") Queue topicQueue, @Qualifier("topicExchange") Exchange topicExchange) {
return BindingBuilder.bind(topicQueue).to(topicExchange).with("topic.#").noargs();
}
}
生产者
@Autowired
private RabbitTemplate rabbitTemplate;
public String sendMessage(String message) {
Message messageBody = new Message(message.getBytes());
rabbitTemplate.convertAndSend("topic_exchange", routing, messageBody);
return "发送成功";
}
消费者
@Component
public class RabbitListenerComponent {
// 绑定要监听的队列
@RabbitListener(queues = "topic_queue")
public void printMessage(Message message) throws IOException {
System.out.println(new String(message.getBody()));
}
测试
调用生产者方法发送消息,消费者会自动监听队列,如果有消息入队,则控制台成功打印出消息