Spring Boot Application as a Service – Spring Boot应用即服务

最后修改: 2016年 9月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This article explores some options of running Spring Boot applications as a service.

本文探讨了将Spring Boot应用作为服务运行的一些选择。

Firstly, we are going to explain web applications’ packaging options and system services. In the subsequent sections, we explore different alternatives we have when setting up a service for both Linux as Windows based systems.

首先,我们将解释网络应用程序的打包选项和系统服务。在随后的章节中,我们将探讨在为基于Linux和Windows的系统设置服务时的不同选择。

Finally, we will conclude with some references to additional sources of information.

最后,我们将以一些其他信息来源的参考资料作为结束。

2. Project Setup and Build Instructions

2.项目设置和构建说明

2.1. Packaging

2.1.包装

Web applications are traditionally packaged as a Web Application aRchives (WAR) and deployed to a web server.

网络应用程序传统上被打包成网络应用程序档案(WAR)并部署到网络服务器上。

Spring Boot applications may be packaged both as WAR and JAR files. The latter embeds a web server within a JAR file, which allows you to run applications without the need of an installation and configuration of an application server.

Spring Boot应用程序可以被打包成WAR和JAR文件。后者在JAR文件中嵌入了一个网络服务器,这使得你可以在不需要安装和配置应用服务器的情况下运行应用程序。

2.2. Maven Configuration

2.2.Maven配置

Let’s start by defining the configuration of our pom.xml file:

让我们从定义我们的pom.xml文件的配置开始。

<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>

<dependencies>
    ....
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

The packaging must be set to jar. We are using the latest stable version of Spring Boot at the time of writing, but any version after 1.3 will be enough. You can find more information about available versions here.

包装必须设置为jar。在撰写本文时,我们使用的是Spring Boot的最新稳定版本,但1.3之后的任何版本都足够了。您可以在这里找到有关可用版本的更多信息

Notice that we have set the <executable> parameter to true for the spring-boot-maven-plugin artifact. This makes sure that a MANIFEST.MF file is added to the JAR package. This manifest contains a Main-Class entry that specifies which class defines the main method for your application.

注意,我们为spring-boot-maven-plugin工件设置了<executable>参数为true。这确保了JAR包中添加了一个MANIFEST.MF文件。该清单包含一个Main-Class条目,指定哪个类定义了应用程序的主方法。

2.3. Building Your Application

2.3.构建你的应用程序

Run the following command inside your application’s root directory:

在你的应用程序的根目录下运行以下命令。

$ mvn clean package

The executable JAR file is now available in the target directory and we may start up the application by executing the following command on the command line:

可执行的JAR文件现在在target目录下可用,我们可以通过在命令行上执行以下命令来启动该应用程序。

$ java -jar your-app.jar

At this point, you still need to invoke the Java interpreter with the -jar option. There are many reasons why it would be preferable to have your app started by being able to invoke it as a service.

在这一点上,你仍然需要用-jar选项来调用Java解释器。有很多理由表明,让你的应用程序通过能够作为一个服务来调用它来启动是比较好的。

3. On Linux

3.在Linux上

In order to run a program as a background process, we could simply use the nohup Unix command, but this is not the preferred way either for various reasons. A good explanation is provided in this thread.

为了将一个程序作为后台进程运行,我们可以简单地使用nohup Unix命令,但由于各种原因,这也不是首选的方法。在这个主题中提供了一个很好的解释。

Instead, we are going to daemonize our process. Under Linux, we may choose to configure a daemon either with a traditional System V init script or with a Systemd configuration file. The former is traditionally the most well-known option but is gradually being replaced by the latter.

相反,我们要对进程进行daemonize。在Linux下,我们可以选择用传统的System V init脚本或Systemd配置文件来配置一个守护程序。前者是传统上最著名的选择,但正逐渐被后者取代。

You may find more details on this difference here.

你可以在这里找到关于这种差异的更多细节

For enhanced security we first create a specific user to run the service with and change the executable JAR file permissions accordingly:

为了增强安全性,我们首先创建一个特定的用户来运行服务,并相应地改变可执行JAR文件的权限。

$ sudo useradd baeldung
$ sudo passwd baeldung
$ sudo chown baeldung:baeldung your-app.jar
$ sudo chmod 500 your-app.jar

3.1. System V Init

3.1.系统V启动

A Spring Boot executable JAR file makes the service setup process very easy:

一个Spring Boot可执行的JAR文件使服务设置过程非常容易。

$ sudo ln -s /path/to/your-app.jar /etc/init.d/your-app

The above command creates a symbolic link to your executable JAR file. You must use the full path to your executable JAR file, otherwise, the symbolic link will not work properly. This link enables you to start the application as a service:

上述命令为你的可执行JAR文件创建一个符号链接。你必须使用可执行JAR文件的完整路径,否则,符号链接将不能正常工作。这个链接使你能够将应用程序作为服务启动。

$ sudo service your-app start

The script supports the standard service start, stop, restart and status commands. Moreover:

该脚本支持标准服务startstoprestartstatus命令。此外。

  • it starts the services running under the user baeldung we have just created
  • it tracks the application’s process ID in /var/run/your-app/your-app.pid
  • it writes console logs to /var/log/your-app.log, which you may want to check in case your application fails to start properly

3.2. Systemd

3.2. Systemd

The systemd service setup is very simple as well. Firstly, we create a script named your-app.service using the following example and put it in /etc/systemd/system directory:

systemd服务的设置也非常简单。首先,我们用下面的例子创建一个名为your-app.service的脚本,并把它放在/etc/systemd/system目录下。

[Unit]
Description=A Spring Boot application
After=syslog.target

[Service]
User=baeldung
ExecStart=/path/to/your-app.jar SuccessExitStatus=143 

[Install] 
WantedBy=multi-user.target

Remember to modify Description, User and ExecStart fields to match your application. You should be able to execute the aforementioned standard service commands at this point as well.

记得修改DescriptionUserExecStart字段以匹配你的应用程序。在这一点上,你也应该能够执行上述的标准服务命令。

As opposed to the System V init approach described in the previous section, the process ID file and console log file should be configured explicitly using appropriate fields in the service script. An exhaustive list of options may be found here.

与上一节所述的System V init方法相反,应该使用服务脚本中的适当字段明确配置进程ID文件和控制台日志文件。一个详尽的选项清单可以在这里找到。

3.3. Upstart

3.3.起步阶段

Upstart is an event-based service manager, a potential replacement for the System V init that offers more control on the behavior of the different daemons.

Upstart是一个基于事件的服务管理器,是System V init的潜在替代品,对不同守护进程的行为提供了更多控制。

The site has good setup instructions that should work for almost any Linux distribution. When using Ubuntu you probably have it installed and configured already (check if there are any jobs with a name starting with “upstart” in /etc/init).

该网站有很好的设置说明,应该适用于几乎所有Linux发行版。当使用Ubuntu时,你可能已经安装并配置了它(检查/etc/init中是否有任何名称以 “upstart “开头的工作)。

We create a job your-app.conf to start our Spring Boot application:

我们创建一个工作your-app.conf来启动我们的Spring Boot应用程序。

# Place in /home/{user}/.config/upstart

description "Some Spring Boot application"

respawn # attempt service restart if stops abruptly

exec java -jar /path/to/your-app.jar

Now run “start your-app” and your service will start.

现在运行 “start your-app”,你的服务就会启动。

Upstart offers many job configuration options, you can find most of them here.

Upstart提供了许多工作配置选项,你可以在这里找到大部分的选项

4. On Windows

4.在Windows

In this section, we present a couple of options that may be used to run a Java JAR as a Windows service.

在这一节中,我们将介绍几个可用于将Java JAR作为Windows服务运行的选项。

4.1. Windows Service Wrapper

4.1.Windows服务封装器

Due to difficulties with the GPL license of the Java Service Wrapper (see next subsection) in combination with e.g. the MIT license of Jenkins, the Windows Service Wrapper project, also known as winsw, was conceived.

由于Java服务封装器的GPL许可证(见下一小节)与例如Jenkins的MIT许可证相结合存在困难,因此设想了Windows服务封装器项目,也被称为winsw

Winsw provides programmatic means to install/uninstall/start/stop a service. In addition, it may be used to run any kind of executable as a service under Windows, whereas Java Service Wrapper, as implied by its name, only supports Java applications.

Winsw提供了安装/卸载/启动/停止服务的程序化手段。此外,它可以被用来在Windows下作为服务运行任何种类的可执行文件,而Java服务封装器,正如其名称所暗示的,只支持Java应用程序。

First, you download the binaries here. Next, the configuration file that defines our Windows service, MyApp.xml, should look like this:

首先,你下载二进制文件这里。接下来,定义我们的Windows服务的配置文件,MyApp.xml,应该是这样的。

<service>
    <id>MyApp</id>
    <name>MyApp</name>
    <description>This runs Spring Boot as a Service.</description>
    <env name="MYAPP_HOME" value="%BASE%"/>
    <executable>java</executable>
    <arguments>-Xmx256m -jar "%BASE%\MyApp.jar"</arguments>
    <logmode>rotate</logmode>
</service>

Finally, you have to rename the winsw.exe to MyApp.exe so that its name matches with the MyApp.xml configuration file. Thereafter you can install the service like so:

最后,你必须将winsw.exe重命名为MyApp.exe,使其名称与MyApp.xml配置文件相符。此后,你可以像这样安装服务。

$ MyApp.exe install

Similarly, you may use uninstall, start, stop, etc.

同样,你可以使用uninstallstartstop,等等。

4.2. Java Service Wrapper

4.2.Java服务封装器

In case you don’t mind the GPL licensing of the Java Service Wrapper project, this alternative may address your needs to configure your JAR file as a Windows service equally well. Basically, the Java Service Wrapper also requires you to specify in a configuration file which specifies how to run your process as a service under Windows.

如果您不介意Java Service Wrapper项目的GPL许可,这个替代方案可能同样能满足您将JAR文件配置为Windows服务的需求。基本上,Java Service Wrapper还要求您在一个配置文件中指定如何在Windows下将您的进程作为一个服务运行。

This article explains in a very detailed way how to set up such an execution of a JAR file as a service under Windows, so we there’s no need to repeat the info.

这篇文章以非常详细的方式解释了如何在Windows下将JAR文件设置为服务执行,所以我们没有必要重复这些信息。

5. Additional References

5.其他参考文献

Spring Boot applications may also be started as Windows service using Procrun of the Apache Commons Daemon project. Procrun is a set of applications that allow Windows users to wrap Java applications as Windows services. Such a service may be set to start automatically when the machine boots and will continue to run without any user being logged on.

Spring Boot 应用程序也可以使用Apache Commons Daemon项目的Procrun作为 Windows 服务启动。Procrun是一组应用程序,允许Windows用户将Java应用程序包装成Windows服务。这样的服务可以被设置为在机器启动时自动启动,并在没有任何用户登录的情况下继续运行。

More details on starting Spring Boot applications under Unix may be found here. There are also detailed instructions on how to modify Systemd unit files for Redhat based systems. Finally

关于在 Unix 下启动 Spring Boot 应用程序的更多细节可在此处找到。还有关于如何为基于 Redhat 的系统修改Systemd 单位文件的详细说明。最后

Finally, this quick howto describes how to incorporate a Bash script into your JAR file, so that it becomes an executable itself!

最后,这个快速方法描述了如何将Bash脚本纳入你的JAR文件,使其本身成为一个可执行文件

6. Conclusion

6.结论

Services allow you to manage your application state very efficiently and, as we have seen, service setup for Spring Boot applications is now easier than ever.

服务允许你非常有效地管理你的应用程序状态,正如我们所看到的,现在Spring Boot应用程序的服务设置比以往任何时候都要简单。

Just remember to follow the important and simple security measures on user permissions to run your service.

只要记得遵循关于用户权限的重要而简单的安全措施来运行你的服务。