首页 > 解决方案 > 如何在 Spring Boot 中运行所需次数的方法?

问题描述

我正在学习 RabbitMq,只是想发送所需的消息次数。我有发送消息以进行交换的 Sender 类,我想重复几次。我正在使用预定的注释,但它有不同的目的,并且与我不匹配,因为它不会停止。

@Scheduled(initialDelay = 1000,fixedDelay = 1500)
    public void sendNumbers(){
        int index = atomicInteger.getAndIncrement();
        UUID uuid = uuids.get(index);
        Pair<Integer,Integer> pair = sumPair.get(uuid);
        MessagePostProcessor messagePostProcessor = message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setCorrelationId(uuid.toString());
            messageProperties.setReplyTo(response.getName());
            return message;
        };
        rabbitTemplate.convertAndSend(directExchange.getName(),routingKey,pair,messagePostProcessor);
    }

我该怎么做?

标签: javaspring-bootrabbitmqspring-amqpspring-rabbit

解决方案


只需使用for循环重复您想要的次数。

您可以在ApplicationRunner.

@Bean
ApplicationRunner runner(RabbitTemplate template) {
    return () -> {
        for (int i = 0; i < 10; i++) {
            ...
            template.convertAndSend(...)
        }
    };

推荐阅读