Java 按编程方式关闭Spring Boot应用程序后关闭电脑
我有一个特殊的用例。我的Raspberry上有一个Spring boot应用程序。此应用程序在Raspberry启动时自动启动。我想发送一个远程命令来重新启动或关闭覆盆子,但我需要首先正确关闭我的Spring Boot应用程序 此应用程序使用H2数据库和SmsLib,需要一点时间才能关闭(10/20秒) 我的想法是拦截远程请求,然后尝试通过以下方式以编程方式关闭应用程序:Java 按编程方式关闭Spring Boot应用程序后关闭电脑,java,spring,spring-boot,h2,Java,Spring,Spring Boot,H2,我有一个特殊的用例。我的Raspberry上有一个Spring boot应用程序。此应用程序在Raspberry启动时自动启动。我想发送一个远程命令来重新启动或关闭覆盆子,但我需要首先正确关闭我的Spring Boot应用程序 此应用程序使用H2数据库和SmsLib,需要一点时间才能关闭(10/20秒) 我的想法是拦截远程请求,然后尝试通过以下方式以编程方式关闭应用程序: applicationContext.close(); 然后,在my custom ApplicationListener
applicationContext.close();
然后,在my custom ApplicationListener中,我读取了应该执行的命令(重新启动或停止),然后执行以下操作:
Runtime.getRuntime().exec("reboot");
这是我的上下文closedevent的相关部分:
@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
private String commandToExecute;
public void onApplicationEvent(ContextClosedEvent event) {
try {
if (commandToExecute != null) {
Runtime.getRuntime().exec(commandToExecute);
}
} catch (Throwable e) {
log.error("Errore durante l'esecuzione del comando <" + commandToExecute + ">", e);
}
}
@组件
公共类ContextClosedHandler实现ApplicationListener{
私有字符串命令执行;
Application event(ContextClosedEvent事件)上的公共无效{
试一试{
if(commandToExecute!=null){
Runtime.getRuntime().exec(commandToExecute);
}
}捕获(可丢弃的e){
日志错误(“错误durante l'esecuzione del comando”,e);
}
}
然而,我认为这不是100%的正确方法。我应该确保只有在我的应用程序中的所有内容都终止时(与db、侦听器、处理程序、ecc的连接)才能重新启动或关闭我的Raspberry。你有更好的主意吗
谢谢!最好有一个外部脚本,告诉你的应用程序关闭,等待它,然后重新启动。没有办法在主应用程序内部以更可靠的方式管理它吗?对于初学者来说,这将是一个测试和维护的噩梦。关注点分离。想必你还是想在启动时启动此服务?是的,应该这样做无论如何启动,然后使用初始化脚本,并作为正常关闭例程的一部分关闭启动应用程序。