SpringBoot 集成RabbitMQ
Posted 追风筝的少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 集成RabbitMQ相关的知识,希望对你有一定的参考价值。
1、application.yml 配置
spring:
rabbitmq:
host: localhost
port: 5672
listener:
simple:
acknowledge-mode: manual // 手动签发
prefetch: 1
retry:
enabled: true
initial-interval: 60000 # 第一次和第二次尝试发布或传递消息间隔: 1分钟
max-attempts: 8
max-interval: 7200000 # 最大重试时间间隔:2小时
multiplier: 2 # 应用于上一重试间隔的乘数
2、RabbitConfig
配置 交换机,队列,交换机与队列的绑定,消息监视容器:
@Configuration
@Data
public class RabbitMQConfig {
final static String queueName = "spring-boot";
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("spring-boot-exchange");
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(queueName);
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
return container;
}
@Bean
Receiver receiver() {
return new Receiver();
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
}
3、生产者
@RestController public class Test { @Autowired RabbitTemplate rabbitTemplate; @RequestMapping(value = "/test/{abc}",method = RequestMethod.GET) public String test(@PathVariable(value = "abc") String abc){ rabbitTemplate.convertAndSend("spring-boot", abc + " from RabbitMQ!"); return "abc"; } }
4、消费者
public class Receiver { private CountDownLatch latch = new CountDownLatch(1); public void receiveMessage(String message) { System.out.println("Received <" + message + ">"); latch.countDown(); } public CountDownLatch getLatch() { return latch; } }
--- 参见: https://www.jianshu.com/p/a5f7fce67803
以上是关于SpringBoot 集成RabbitMQ的主要内容,如果未能解决你的问题,请参考以下文章
分布式WebSocket - 4SpringBoot集成STOMP协议,RabbitMQ为消息代理
RabbitMQ——SpringBoot集成RabbitMQ
RabbitMQ——SpringBoot集成RabbitMQ
SpringBoot - SpringBoot集成RabbitMQ