Обучение Spring Boot (5): настройка кода завершения процесса

Spring Boot

В онлайн-среде приложение может быть прекращено из-за некоторых исключений.Если нам нужно вовремя найти причину, согласноexit codeПозиционирование — хороший способ.spring bootПредоставляет соответствующие интерфейсы для разработчиков, чтобы облегчить разработчикам определение собственных типов исключений.exit code:ExitCodeGeneratorа такжеExitCodeExceptionMapper.

1. ExitCodeGenerator:

Используется для активного выхода из приложения, вSpringApplication.exit(org.springframework.context.ApplicationContext,ExitCodeGenerator..)используется в , этот метод найдет всеExitCodeGeneratorизBean, также будет использовать объект параметра в методе.

ExitCodeGeneratorЗаявление выглядит следующим образом:

@FunctionalInterface
public interface ExitCodeGenerator {

    /**
     * Returns the exit code that should be returned from the application.
     * @return the exit code.
     */
    int getExitCode();

}

1.1 Использование:

System.exit(SpringApplication.exit(SpringApplication.run(DemoApplication.class, args)));


@SpringBootApplication
public class DemoApplication{

    @Bean
    public ExitCoder getTestExitCoder(){
        return new ExitCoder();
    }

    @Bean
    public ExitCoder1 getTestExitCoder1(){
        return new ExitCoder1();
    }


    public static void main(String[] args) {
        System.exit(SpringApplication.exit(SpringApplication.run(DemoApplication.class, args)));
    }
}
import org.springframework.boot.ExitCodeGenerator;


public class ExitCoder implements ExitCodeGenerator {
    @Override
    public int getExitCode() {
        System.out.println("get exit code from class: ExitCoder");
        return 222;
    }
}
import org.springframework.boot.ExitCodeGenerator;

public class ExitCoder1 implements ExitCodeGenerator {
    @Override
    public int getExitCode() {
        System.out.println("get exit code from class: ExitCoder1");
        return 221;
    }
}

Выход


2019-03-21 21:52:55.802  INFO 44627 --- [           main] com.example.exitcode.DemoApplication     : Starting DemoApplication on lei.local with PID 44627 (/Users/lei/own/projects/java_learning/spring_boot_learning/blog/5exitcode/exitcode/out/production/classes started by lei in /Users/lei/own/projects/java_learning/spring_boot_learning/blog/5exitcode/exitcode)
2019-03-21 21:52:55.806  INFO 44627 --- [           main] com.example.exitcode.DemoApplication     : No active profile set, falling back to default profiles: default
2019-03-21 21:52:56.339  INFO 44627 --- [           main] com.example.exitcode.DemoApplication     : Started DemoApplication in 15.901 seconds (JVM running for 21.676)
get exit code from class: ExitCoder
get exit code from class: ExitCoder1
Disconnected from the target VM, address: '127.0.0.1:50873', transport: 'socket'

Process finished with exit code 222

Как видно из вышеизложенного, сexit codeНаибольшее значение является окончательным.

2. ExitCodeExceptionMapper:

Используется, когда в приложении возникает нерегулируемое исключение, вызывающее выход из приложения. Заявление выглядит следующим образом:

@FunctionalInterface
public interface ExitCodeExceptionMapper {

    /**
     * Returns the exit code that should be returned from the application.
     * @param exception the exception causing the application to exit
     * @return the exit code or {@code 0}.
     */
    int getExitCode(Throwable exception);

}

2.1 Как использовать

пройти черезBeanЧтобы зарегистрировать, когда в приложении возникает исключение, каждыйExitCodeExceptionMapperкласс реализации. Здесь мы можем установить свои собственные в соответствии с типом исключенияexit code:

@SpringBootApplication
public class DemoApplication{
    @Bean
    public DemoExitCodeExceptionMapper getExitCodeMapper(){
        return new DemoExitCodeExceptionMapper();
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @Bean
    CommandLineRunner showUsers() {
        return args -> {throw new Exception("xxxxx");};
    }
}

public class DemoExitCodeExceptionMapper implements ExitCodeExceptionMapper{
    /**
     * Returns the exit code that should be returned from the application.
     * @param exception the exception causing the application to exit
     * @return the exit code or {@code 0}.
     */
    @Override
    public int getExitCode(Throwable exception){
        System.out.println("exit cod xxxx" + exception.getMessage());
        if(exception.getCause().getMessage().equals("sdf")){
            return 254;
        }
        return 243;
    }
}

Результат работы:

2019-03-21 22:13:34.261  INFO 45049 --- [           main] com.example.exitcode.DemoApplication     : Started DemoApplication in 15.816 seconds (JVM running for 21.521)
exit cod xxxxFailed to execute CommandLineRunner
2019-03-21 22:13:38.797  INFO 45049 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-03-21 22:13:38.845 ERROR 45049 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at com.example.exitcode.DemoApplication.main(DemoApplication.java:31) [classes/:na]
Caused by: java.lang.Exception: xxxxx
    at com.example.exitcode.DemoApplication.lambda$showUsers$0(DemoApplication.java:37) [classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    ... 5 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:51237', transport: 'socket'

Process finished with exit code 243

3. Логика ценности

public int getExitCode() {
    int exitCode = 0;
    for (ExitCodeGenerator generator : this.generators) {
        try {
            int value = generator.getExitCode();
            if (value > 0 && value > exitCode || value < 0 && value < exitCode) {
                exitCode = value;
            }
        }
        catch (Exception ex) {
            exitCode = (exitCode != 0) ? exitCode : 1;
            ex.printStackTrace();
        }
    }
    return exitCode;
}
  1. Первый: возьмите значение первого напрямую.
  2. 2....n-1,n: nа такжеn-1Положительное и отрицательное разные, возьмитеn, то же, взять большее абсолютное значение.

4. Резюме:

  • Активный вызовSpringApplication.exitиспользование методаExitCodeGenerator, в состоянии пройтиBeanРегистрация также может быть передана по значению.
  • Приложение аварийно завершает работуExitCodeExceptionMapper, только черезBeanЗарегистрируйтесь, чтобы использовать.
  • Ценность: Положительное и отрицательное значение спереди и сзади разные, берите самые последние, одинаковые, берите большее абсолютное значение.