第一种方法
(平常前后端分离时可以使用,但项目打包成jar包后,使用的devtools依赖导致启动jar包失败)
前端创建一个按钮,调用该api即可。
<el-button size="medium" round type="primary" icon="el-icon-refresh" style="color: black" @click="restart">重新启动服务器
</el-button>
前端methods方法
restart(){
this.$http.post('/restart').then(res => {
if(res.data){
console.log(res.data)
this.$message({
message:'正在重启服务!',
type: 'success',
offset: 350,
showClose: true
})
}
else {
this.$message({
message:'重启服务失败!',
type: 'success',
offset: 350,
showClose: true
})
}
})
}
后端代码
@CrossOrigin
@PostMapping(value="api/restart")
@ResponseBody
public boolean restart() {
Restarter restarter = Restarter.getInstance();
restarter.restart(new FailureHandler() {
public Outcome handle(Throwable failure) {
System.out.println("重启失败");
return Outcome.ABORT;
}
});
return true;
}
导入依赖
org.springframework.boot
spring-boot-devtools
true
第二种方法
亲测可行,参考连接
https://duoduokou.com/java/50894250288586716926.html
这是我的后台启动类,在里面加了个重启的方法
package com.example.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication(scanBasePackages = "com.example.demo")
public class Demo1Application {
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(Demo1Application.class, args);
}
public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(Demo1Application.class, String.valueOf(args));
});
thread.setDaemon(false);
thread.start();
}
}
编写接口
@Controller
public class RestartController {
@CrossOrigin
@PostMapping(value="api/restart")
@ResponseBody
public boolean restart() {
DemoApplication.restart();
return true;
}
}