0

请注意: Commons Daemon 自2013 年以来没有发布过。因此,如果有更现代的替代方案(与 更兼容systemd),那么我会全神贯注并接受任何想法!


我正在尝试将我的 Java 8 应用程序部署为由systemd. 我已经阅读了Commons Daemon文档,我相信实现这一点的方法如下:

  1. 写一个systemd服务单元文件,比如说一个/lib/systemd/system/myapp.service文件;这将允许我通过systemctl start myapp等手动控制我的应用程序,还允许我执行以下操作:将我的应用程序配置为在 Linux 启动时启动,如果它崩溃,总是尝试重新启动等。
  2. 然后我还需要实现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(...)方法。有任何想法吗?

4

0 回答 0