1

I've written a small library for creating services/daemons in Java. The idea is simple. When you start your application you pass a command and a port number. If the command is a start command, a new instance of your application will be started on the specified port. Otherwise, the command will be sent to any instance that might be running on that port.

In short, the library provides a daemonize method that starts a daemon controller thread. It uses sockets to make your application communicate with instances of itself (as you've probably already figured out).

For clarity, here's an example of how you would use it:

public class MyApp extends Daemon
{
    public static void main(String[] args)
    {
        if (daemonize(MyApp.class, args))
        {
            // normal main body
            startMyServerOrWhatever();
        }
        else
        {
            // failed to start or send command to daemon
            // probably wrong syntax or unknown command
            printUsageInfoAndExit();
        }
    }

    @Command(start = true)
    public static int start()
    {
        // executed on "start" command, e.g. java -jar MyApp.jar start 8899
        doSomeInitializing();
        return 0; // return 0 or void to detach from console
    }

    @Command
    public static void mycmd()
    {
        // executed on "mycmd" command, i.e. java -jar MyApp.jar mycmd 8899
        doSomethingCool();
    }

    @Command(stop = true)
    public static int stop()
    {
        // executed on "stop" command, i.e. java -jar MyApp.jar stop 8899
        doSomeCleanup();
        return 0; // used as application exit code
    }
}

The library works really well and I've used it to create a couple of daemons that will run on a Linux server. What's missing now is some scripts to let the admins control these daemons like they control other daemons on the server (e.g. start at boot).

Unfortunately my *nix skills, especially when it comes to scripting, are not top level. I have a basic understanding of the BSD-style init procedure (rc.d), but looking at sample scripts like this one I feel a little lost.

So my question is, isn't there a simpler way to do this in my case? I mean, my daemons already understand the commands and should themselves be responsible for any actions (except in the case where a daemon doesn't respond to stop - it should then be killed after some timeout).

4

2 回答 2

1

你真的应该看看 tanuki 软件的 java 服务包装器。
http://wrapper.tanukisoftware.com/

我喜欢他们的方法的地方在于,他们使用单一工具和通用脚本标准化了守护进程和 Windows 服务进程。

我注意到这个工具在一些知名项目(如 nexus、servicemix 等)中的采用程度很高。

而当我遇到一个项目采用 Java Service Wrapper 来管理守护进程时,命令集和配置对我来说已经很熟悉了,这降低了学习曲线。

也许您可以将您的套接字控制器机制安装到这个现有的框架中。

于 2011-03-08T09:19:32.690 回答
0

没有更简单的方法吗

我编写了一次守护程序脚本来通过 SSH 启动我们的 java 应用程序。它们是极简主义的——没有强制终止或 rc.d/SMF 集成,只有使用 TERM 信号的守护程序启动和关闭。

于 2012-10-27T13:36:08.557 回答