SimpleMessageListenerContainer Amazon SQS Pollinterval

Я использую библиотеку 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;
}
4
0
2 031
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вызовите функцию setWaitTimeOut (N) базового класса AbstractMessageListenerContainer в пакете org.springframework.cloud.aws.messaging.listener. N - длительный тайм-аут опроса в секундах. Например, если вы хотите подождать 5 секунд, прежде чем он вернется, используйте следующую строку кода в своей функции queueMessageHandler (). По умолчанию это 1 секунда, если вы не вызываете эту функцию. Максимальный длительный тайм-аут опроса составляет 20 секунд, поэтому максимальное значение, которое вы можете дать этой функции, равно 20, что означает «подождите 20 секунд».

simpleMessageListenerContainer.setWaitTimeOut (5);

Исходный код здесь: https://github.com/spring-cloud/spring-cloud-aws/blob/master/spring-cloud-aws-messaging/src/main/java/org/springframework/cloud/aws/messaging/listener/AbstractMessageListenerContainer. Ява

/**
     * 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;
    }

Спасибо @Raj. В чем разница между этим и длинным интервалом опроса, который задается как часть конфигурации SQS в консоли AWS?

Punter Vicky 03.05.2018 13:38

Хороший вопрос. В справке указано: «Максимальное время, в течение которого вызов приема с длительным опросом будет ждать появления сообщения перед возвратом пустого ответа». Насколько я понимаю, если вы установите 15 секунд как максимум в консоли, вы можете выбрать от 1 до 15 в клиенте Java.

Raj 03.05.2018 14:27

Спасибо, попробую.

Punter Vicky 03.05.2018 14:30

@PunterVicky Согласно документам AWS положительное значение в запросах на опрос побеждает атрибут очереди: для параметра WaitTimeSeconds действия ReceiveMessage значение, установленное между 1 и 20, имеет приоритет над любым значением, установленным для атрибута очереди ReceiveMessageWaitTimeSeconds (см. docs.aws.amazon.com/AWSSimpleQueueService/latest/…)

Moose on the Loose 24.04.2019 22:30

@Raj Вы предлагаете расширить AbstractMessageListenerContainer? Или доступ к SimpleMessageListenerContainer через контекст приложения Spring и изменение настройки?

Moose on the Loose 24.04.2019 22:33

Обратите внимание, что по умолчанию тайм-аут установлен на 20 секунд в коде Spring Cloud, начиная с версии 2.0.0, подробности см. В этой проблеме: github.com/spring-cloud/spring-cloud-aws/issues/319

Moose on the Loose 26.04.2019 18:07

Другие вопросы по теме