Я использую библиотеку Spring Cloud для опроса SQS. Как я могу установить интервал опроса?
@Bean
@Primary
public AmazonSQSAsync amazonSQSAsync() {
return AmazonSQSAsyncClientBuilder.standard().
withCredentials(awsCredentialsProvider()).
withClientConfiguration(clientConfiguration()).
build();
}
@Bean
@ConfigurationProperties(prefix = "aws.queue")
public SimpleMessageListenerContainer simpleMessageListenerContainer(AmazonSQSAsync amazonSQSAsync) {
SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
simpleMessageListenerContainer.setMessageHandler(queueMessageHandler());
simpleMessageListenerContainer.setMaxNumberOfMessages(10);
simpleMessageListenerContainer.setTaskExecutor(threadPoolTaskExecutor());
return simpleMessageListenerContainer;
}
@Bean
public QueueMessageHandler queueMessageHandler() {
QueueMessageHandlerFactory queueMessageHandlerFactory = new QueueMessageHandlerFactory();
queueMessageHandlerFactory.setAmazonSqs(amazonSQSAsync());
QueueMessageHandler queueMessageHandler = queueMessageHandlerFactory.createQueueMessageHandler();
return queueMessageHandler;
}
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(10);
executor.setThreadNamePrefix("oaoQueueExecutor");
executor.initialize();
return executor;
}
Вызовите функцию setWaitTimeOut (N) базового класса AbstractMessageListenerContainer в пакете org.springframework.cloud.aws.messaging.listener. N - длительный тайм-аут опроса в секундах. Например, если вы хотите подождать 5 секунд, прежде чем он вернется, используйте следующую строку кода в своей функции queueMessageHandler (). По умолчанию это 1 секунда, если вы не вызываете эту функцию. Максимальный длительный тайм-аут опроса составляет 20 секунд, поэтому максимальное значение, которое вы можете дать этой функции, равно 20, что означает «подождите 20 секунд».
simpleMessageListenerContainer.setWaitTimeOut (5);
/**
* Configures the wait timeout that the poll request will wait for new message to arrive if the are currently no
* messages on the queue. Higher values will reduce poll request to the system significantly.
*
* @param waitTimeOut
* - the wait time out in seconds
*/
public void setWaitTimeOut(Integer waitTimeOut) {
this.waitTimeOut = waitTimeOut;
}
Хороший вопрос. В справке указано: «Максимальное время, в течение которого вызов приема с длительным опросом будет ждать появления сообщения перед возвратом пустого ответа». Насколько я понимаю, если вы установите 15 секунд как максимум в консоли, вы можете выбрать от 1 до 15 в клиенте Java.
Спасибо, попробую.
@PunterVicky Согласно документам AWS положительное значение в запросах на опрос побеждает атрибут очереди: для параметра WaitTimeSeconds действия ReceiveMessage значение, установленное между 1 и 20, имеет приоритет над любым значением, установленным для атрибута очереди ReceiveMessageWaitTimeSeconds (см. docs.aws.amazon.com/AWSSimpleQueueService/latest/…)
@Raj Вы предлагаете расширить AbstractMessageListenerContainer? Или доступ к SimpleMessageListenerContainer через контекст приложения Spring и изменение настройки?
Обратите внимание, что по умолчанию тайм-аут установлен на 20 секунд в коде Spring Cloud, начиная с версии 2.0.0, подробности см. В этой проблеме: github.com/spring-cloud/spring-cloud-aws/issues/319
Спасибо @Raj. В чем разница между этим и длинным интервалом опроса, который задается как часть конфигурации SQS в консоли AWS?