我不明白SQS QueueListener是如何工作的。
这是我的配置:
/**
* AWS Credentials Bean
*/
@Bean
public AWSCredentials awsCredentials() {
return new BasicAWSCredentials(accessKey, secretAccessKey);
}
/**
* AWS Client Bean
*/
@Bean
public AmazonSQS amazonSQSAsyncClient() {
AmazonSQS sqsClient = new AmazonSQSClient(awsCredentials());
sqsClient.setRegion(Region.getRegion(Regions.US_EAST_1));
return sqsClient;
}
/**
* AWS Connection Factory
*/
@Bean
public SQSConnectionFactory connectionFactory() {
SQSConnectionFactory.Builder factoryBuilder = new SQSConnectionFactory.Builder(
Region.getRegion(Regions.US_EAST_1));
factoryBuilder.setAwsCredentialsProvider(new AWSCredentialsProvider() {
@Override
public AWSCredentials getCredentials() {
return awsCredentials();
}
@Override
public void refresh() {
}
});
return factoryBuilder.build();
}
/**
* Registering QueueListener for queueName
*/
@Bean
public DefaultMessageListenerContainer defaultMessageListenerContainer() {
DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
messageListenerContainer.setConnectionFactory(connectionFactory());
messageListenerContainer.setDestinationName(queueName);
messageListenerContainer.setMessageListener(new MessageListenerAdapter(new LabQueueListener()));
messageListenerContainer.setErrorHandler(new QueueListenerErrorHandler());
messageListenerContainer.setTaskExecutor(Executors.newFixedThreadPool(3));
return messageListenerContainer;
}
如您所见,我已将DefaultMessageListenerContainer
配置为Executors.newFixedThreadPool(3)
这样我希望我的队列侦听器一次执行3个并发任务。
Thsi是我的倾听者逻辑:
public class QueueListener {
public void handleMessage(String messageContent) {
try {
logger.info(String.format("message received: %s", messageContent));
logger.info("wait 30 sec");
Thread.sleep(1000 * 30);
logger.info("done");
} catch (Throwable th) {
throw new QueueListenerException(messageContent, th);
}
}
}
现在每个handleMessage
方法阻止(Thread.sleep(1000 * 30);
)执行30秒,并且一次只执行1 handleMessage
个方法。
我做错了什么?
如何一次实现并发handleMessage
方法调用?
使用当前配置,我希望同时执行3 handleMessage
。
答案 0 :(得分:1)
您可以添加参数以通过添加messageListenerContainer.setConcurrency("3-10");
来处理Bean中为DefaultMessageListenerConfigurator执行的并发执行。这意味着它将从3个线程开始并扩展到10.
也可以使用messageListenerContainer.setConcurrentConsumers(3);