[英]Where's the async part in this Spring AMQP's official sample project?
我目前正在閱讀 Spring AMQP 的官方示例項目以及Spring AMQP 文檔中的相應解釋,它還包括一個帶有代碼的異步示例:
@Configuration
public class ProducerConfiguration {
protected final String helloWorldQueueName = "hello.world.queue";
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setRoutingKey(this.helloWorldQueueName);
return template;
}
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory();
}
@Bean
public ScheduledProducer scheduledProducer() {
return new ScheduledProducer();
}
@Bean
public BeanPostProcessor postProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}
static class ScheduledProducer {
@Autowired
private volatile RabbitTemplate rabbitTemplate;
private final AtomicInteger counter = new AtomicInteger();
@Scheduled(fixedRate = 3000)
public void sendMessage() {
rabbitTemplate.convertAndSend("Hello World " + counter.incrementAndGet());
}
}
}
@Configuration
public class ConsumerConfiguration {
protected final String helloWorldQueueName = "hello.world.queue";
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory();
}
@Bean
public SimpleMessageListenerContainer listenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory());
container.setQueueNames(this.helloWorldQueueName);
container.setMessageListener(new MessageListenerAdapter(new HelloWorldHandler()));
return container;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setRoutingKey(this.helloWorldQueueName);
template.setDefaultReceiveQueue(this.helloWorldQueueName);
return template;
}
@Bean
public Queue helloWorldQueue() {
return new Queue(this.helloWorldQueueName);
}
}
public class HelloWorldHandler {
public void handleMessage(String text) {
System.out.println("Received: " + text);
}
}
正如文檔解釋的那樣:
由於此示例演示了異步消息接收,因此生產端被設計為連續發送消息(如果它是像同步版本一樣的每次執行的消息 model,那么它實際上是一個消息就不會那么明顯了——驅動型消費者)。 負責持續發送消息的組件在 ProducerConfiguration 中定義為內部 class。 它被配置為每三秒運行一次。
我無法理解這段代碼的“異步”是什么,因為根據我的理解,在基本的“同步方式”中,像amqpTemplate.converAndSend()
和amqpTemplate.receiveAndConvert()
這樣的操作已經執行 Rabbitmq 的異步操作,生產者和消費者都不是發送/接收消息時阻塞。
那么,異步部分在哪里? 以及如何理解 Spring AMQP 上下文中的異步與同步? 感謝任何幫助或資源推薦!
使用異步,框架調用MessageListener
; 消息在可用時到達。
使用同步,應用程序調用接收方法,如果沒有消息可用,該方法要么立即返回,要么阻塞直到消息到達或超時到期。
在同步情況下,應用程序控制何時接收消息,而異步則由框架控制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.