小萝卜干的技术分享

15 object(s)
 

Linux 创建针对Java程序的服务

先上service的范例:

[Unit]
Description=Your Description
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/java -jar /xxxx/xxxx.jar
ExecStop=/bin/kill -TERM $MAINPID
Restart=always
SuccessExitStatus=143
TimeoutStopSec=60

[Install]
WantedBy=multi-user.target

其中:

ExecStop选项最好添加上去,在某些系统如CentOS7中,不添加ExecStop则会报错

kill命令后面跟了-TERM,TERM代表SIGTERM(软件终止)。不建议使用-KILL,即SIGKILL(强制杀进程)

关于添加的SuccessExitStatus,有一篇国外的文章对它进行了详细的解释。原文链接:Gracefully killing a Java process managed by systemd – Øyvind Stegard

The JVM process is setup so that it gracefully shuts down the service upon reception of the SIGTERM signal (using shutdown hooks). However, the JVM will still exit with code 143 in the end due to receiving SIGTERM (128+15), and systemd thinks something went wrong when stopping the service. The solution is simple: add SuccessExitStatus=143 to the Unit configuration file for the service, and systemd will consider this code as successful termination. If the graceful shutdown can take some time, add TimeoutStopSec=NN as well to give the service process more time before systemd brings out the big gun.

将这个service保存到/usr/lib/systemd/system目录下,即可通过systemd进行管理

修改完毕后记得先执行systemctl daemon-reload,然后再进行后续的操作