Spring Boot - 重启

最后更新:2019-03-07

1. 方式1


@SpringBootApplication
public class Application {

    private static ConfigurableApplicationContext context;
    
    public static void main(String[] args) {
        context = SpringApplication.run(Application.class, args);
    }
    
    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);
    
        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(Application.class, args.getSourceArgs());
        });
    
        thread.setDaemon(false);
        thread.start();
    }
}

@RestController
public class RestartController {

    @PostMapping("/restart")
    public void restart() {
        Application.restart();
    }
}

$ curl -s -X POST localhost:8080/restart

2. 方式2 RestartEndpoint

引入依赖

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-context</artifactId>
      <version>${cloud.start.version}</version>
    </dependency>

配置

management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: "*"

$ curl -s -X POST localhost:8080/actuator/restart
{"message":"Restarting"}

当然也可以通过RestartEndpoint来在任意地方重启应用


@Service
public class RestartService {

    @Autowired
    private RestartEndpoint restartEndpoint;
     
    public void restartApp() {
        restartEndpoint.restart();
    }
}
Edgar

Edgar
一个略懂Java的小菜比