请注意: Commons Daemon 自2013 年以来没有发布过。因此,如果有更现代的替代方案(与 更兼容systemd
),那么我会全神贯注并接受任何想法!
我正在尝试将我的 Java 8 应用程序部署为由systemd
. 我已经阅读了Commons Daemon文档,我相信实现这一点的方法如下:
- 写一个
systemd
服务单元文件,比如说一个/lib/systemd/system/myapp.service
文件;这将允许我通过systemctl start myapp
等手动控制我的应用程序,还允许我执行以下操作:将我的应用程序配置为在 Linux 启动时启动,如果它崩溃,总是尝试重新启动等。 - 然后我还需要实现
Daemon
接口(来自 Commons Daemon),这将允许我的应用程序“监听”发送给它的事件,systemd
并在某些事情发生时调用正确的 Java 方法(应用程序启动、停止、重新启动、Linux是关机等)。
Daemon
我对这种impl的最佳尝试:
public class MyApp implements Daemon {
private BillingService billingService;
private PizzaDeliveryService pizzaDeliveryService;
public MyApp() {
super();
// Do NOT initialize any services from inside here.
}
public static void main(String[] args) {
MyApp app = new MyApp();
}
@Override
public void init(DaemonContext context) throws DaemonInitException, Exception {
// 1. I assume this is where I do all my initializing,
// and that I don't init anything in my default ctor above?
billingService = new StripBillingService();
pizzaDeliveryService = new LittleCaesarsDeliveryService();
// etc.
}
@Override
public void start() throws Exception {
// 2. This is where my service starts actually doing things,
// firing up other threads, etc.
}
@Override
public void stop() throws Exception {
// 3. Will this respond to a Linux 'sudo shutdown -P now'
// command?
}
@Override
public void destroy() {
// 4. Where I'm supposed to actually release resources
// and terminate gracefully.
}
}
我对Daemon
界面的理解正确吗?MyApp
简单地在内部实例化一个实例是否正确main
,然后 Commons Daemon 负责调用init(...)
和start(...)
为我?我是否正确不初始化任何MyApp
字段或从默认构造函数进行依赖注入,而是从内部进行所有这些操作init(...)
?
更重要的是(我的实际问题):哪些 Linux 命令会触发该stop(...)
方法?
sudo shutdown -P now
我问是因为我打算通过发出或通过关闭服务器,sudo halt -p
并且想知道哪个(如果有)命令将提示systemd
调用该MyApp#stop(...)
方法。有任何想法吗?