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
原文地址:https://www.cnblogs.com/123-shen/p/12221760.html
时间: 2024-11-10 14:01:13