当前版本:SpringBoot2.3.12.RELEASE
、JDK1.8
1. 声明
当前内容主要为本人学习和使用SpringBoot,实现通过web方式控制SpringBoot的程序重启操作,主要参考SpringBoot官方文档
- 通过观察发现重启是与
RemoteSpringApplication
有关 - 查看源码发现与Restarter有关
- 所以可以手动实现
2.源码寻找
RemoteSpringApplication源码
private void run(String[] args) {
Restarter.initialize(args, RestartInitializer.NONE);
SpringApplication application = new SpringApplication(RemoteClientConfiguration.class);
application.setWebApplicationType(WebApplicationType.NONE);
application.setBanner(getBanner());
application.setInitializers(getInitializers());
application.setListeners(getListeners());
application.run(args);
waitIndefinitely();
}
看到主要实现的为Restarter,然后找到Restarter源码
/**
* Restart the running application.
* @param failureHandler a failure handler to deal with application that doesn't start
*/
public void restart(FailureHandler failureHandler) {
if (!this.enabled) {
this.logger.debug("Application restart is disabled");
return;
}
this.logger.debug("Restarting application");
getLeakSafeThread().call(() -> {
Restarter.this.stop();
Restarter.this.start(failureHandler);
return null;
});
}
所以找到了重启的方式
3.重启实现Demo
首先导入devtools依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>false</optional>
</dependency>
注意先导入springboot-parent依赖
为了方便比较是否重启,定义一个随机数用于查看
AppConfig代码
@Configuration
public class AppConfig implements WebMvcConfigurer{
public AppConfig() {
int randomNum = (int)(Math.random()*1000)+1;
System.out.println("AppConfig 实例化成功........."+(randomNum));
}
}
写一个重启controller
@RestController
public class RestartController {
@Autowired
ApplicationContext applicationContext;
@RequestMapping("/restart")
public String restart() {
Restarter restarter = Restarter.getInstance();
restarter.restart(new FailureHandler() {
public Outcome handle(Throwable failure) {
System.out.println("当前系统出现问题,无法重启项目...........");
return Outcome.ABORT;
}
});
return "重启服务成功!";
}
}
启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplicationBuilder(Application.class).build(args);
application.run();
}
}
4. 测试
调用接口后
重新启动了当前的SpringBoot程序了,测试成功