Spring boot 无端口模式启动

tech2025-12-02  22

背景

在服务架构中,有些springboot工程只是简单的作为服务,并不提供web服务。或者并不提供对外的访问服务,这个时候我们只想能以后台进程去运行,因为项目只是作为客户端去做一些操作系统或者去请求其他任务的事情,并不想要启动端口。

我们以Spring Boot (v2.3.3.RELEASE)为例进行讲解。

实现无端口启动

网上说如果要无端口模式,分web项目和非web项目来处理。如果是非web项目就把下面的依赖去掉。

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

对于Sring Boot来讲,我们觉得没必要去除依赖(当然你也可以去掉依赖),就可以让进程常驻内存。具体步骤如下:

(1) 首先我们正常的新建Spring Boot web项目。

(2)修改配置文件: application.properties

# 无端口模式启动web项目 spring.main.web-application-type=none

到处为止,我们启动Spring Boot的时候会自动关闭。因为没有去执行所以就结束了。所以我们可以使用定时任务,从而让它常驻进程并且不启动端口

(3)添加定时任务从而让它常驻进程。(启一个定时任务不做任何事情是为了让进程能常驻内存)

package yeyese.noport.task; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.time.LocalDateTime; @Configuration //1.主要用于标记配置类,兼备Component的效果。 @EnableScheduling // 2.开启定时任务 public class SaticScheduleTask { //3.添加定时任务 @Scheduled(cron = "*/30 * * * * ?") //或直接指定时间间隔,例如:5分钟 private void configureTasks() { System.err.println("测试无端口模式启动,然后执行定时任务: " + LocalDateTime.now()); } }

验证

到此,我们看到进程常驻了,并且没有启动端口。

我们放到Linux服务器上去跑一下看看:

#ps -ef |grep java www 6616 1 6 15:00 ? 00:00:03 java -jar noport-0.0.1-SNAPSHOT.jar root 6689 6670 0 15:01 pts/0 00:00:00 grep --color=auto java #netstat -ntlp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 1/systemd tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1069/sshd tcp6 0 0 :::111 :::* LISTEN 1/systemd tcp6 0 0 :::22 :::* LISTEN 1069/sshd

 

最新回复(0)