如何理解Spring AMQP中的异步与同步



我目前正在阅读Spring AMQP的官方样本项目,以及Spring AMQP文档中的相应解释。该项目涉及syncasync版本,两者仅略有不同。这是异步版本:

生产者配置:

@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);
}
}

HelloWorldHandler:

public class HelloWorldHandler {
public void handleMessage(String text) {
System.out.println("Received: " + text);
}
}

正如文档所解释的:

由于此示例演示了异步消息接收,因此生产端被设计为连续发送消息(如果它是像同步版本那样的每执行一条消息的模型,那么它实际上就不是一个消息驱动的消费者了(。负责连续发送消息的组件被定义为ProducerConfiguration中的内部类。它被配置为每三秒运行一次。

我不明白什么是";异步;关于这个代码,因为,根据我的理解,在一个基本的";"同步方式";,像amqpTemplate.converAndSend()amqpTemplate.receiveAndConvert()这样的操作已经形成了Rabbitmq的异步操作,生产者和消费者在发送/接收消息时都没有阻塞。

那么,在这个例子中异步是如何表现的呢?如何理解Spring AMQP上下文中的异步与同步?

使用async,MessageListener由框架调用;只要有消息,消息就会到达。

使用sync,应用程序调用一个接收方法,如果没有消息可用,该方法会立即返回,或者阻塞,直到消息到达或超时。

在同步的情况下,应用程序控制何时接收消息,使用异步,框架处于控制之中。

最新更新