@EnableScheduling не распознается и не создает службу Executor и выполняет запланированные задания - PullRequest
1 голос
/ 22 июня 2019

Попытка изменить приложение, чтобы @Component имел запланированное задание для запуска каждые n секунд. Кажется, что служба executor никогда не начинает осознавать, что есть @Components, которые имеют аннотацию @Scheduled. Есть идеи?

Убедитесь, что пакеты верны и должны быть в базовом пакете компонентов.


package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * This is the Spring Boot class for the Data Consistency Model (DCM)
 */
@EnableScheduling
@SpringBootApplication
@EnableConfigurationProperties({KafkaConfig.class, SparkConfig.class, JedisConfig.class, PrometheusConfig.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


Component Class:
package com.test;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@EnableScheduling
@EnableAsync
public class PrometheusGatewayMetricsPusher {
    private static final Logger LOGGER = LogManager.getLogger(PrometheusGatewayMetricsPusher.class);
    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    PushGateway pushGateway;

    @Scheduled(fixedDelay = 1000, initialDelay = 1000)
    public void push() {
        try {
            pushGateway.push(CollectorRegistry.defaultRegistry, appName);
        } catch (IOException e) {
            LOGGER.log(Level.ERROR, "Error pushing to gateway. " + e.getMessage());
        }
    }
}

Config Class:
package com.test;
import io.prometheus.client.exporter.PushGateway;
import io.prometheus.client.hotspot.DefaultExports;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Getter
@Setter
@Configuration
public class MetricsConfig {
    @Value("prometheus.config.gateway")
    private String pushGatewayURL;


    @PostConstruct
    public void defaultExports() {
        DefaultExports.initialize();
    }

    @Bean
    public PushGateway pushGateway() {
        return new PushGateway("localhost:9091");
    }
}

Я ожидаю, что служба executor будет запущена и инициализирована в контексте приложения с пулом потоков 1. Затем она будет выполнять метод @Scheduled каждую секунду после начальной задержки в 1 секунду. Если я остановлю точку в классе @Component, она вообще не будет инициализирована.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...