Ohhnews

分类导航

$ cd ..
Baeldung原文

在 IntelliJ IDEA 中运行多个 Spring Boot 实例的两种方法

#spring boot#intellij idea#开发环境#后端开发#应用程序配置

[LOADING...]

1. 简介

在本篇简短的教程中,我们将介绍在 IntelliJ IDEA 中运行多个 Spring Boot 实例的两种实用方法。

在本地开发和测试过程中,运行同一应用程序的多个实例非常有价值。典型的应用场景包括验证不同的配置设置,或模拟不同服务之间的交互。

2. 使用命令行参数

Spring Boot 允许我们在应用启动时通过命令行参数覆盖配置属性。我们可以利用这一特性,为 server.port 配置不同的值,从而决定嵌入式服务器运行的端口。

要运行多个实例,我们可以在 IntelliJ 中创建多个运行配置,并相应地对每个配置进行设置。

首先,进入 Run -> Edit Configurations,创建一个新的配置,并设置常规选项,如主运行类、Java 版本和工作目录。

然后,导航到 Program arguments 字段,使用 --server.port=8081 属性定义端口: [LOADING...]

操作系统要求端口与进程之间必须存在唯一的一对一映射,这意味着我们无法在同一端口上运行多个应用程序。 因此,下一步是复制该配置,并为其分配一个不同的端口参数,例如 --server.port=8082

在运行之前,让我们创建一个简单的 REST 端点来验证应用程序是否已启动并运行:

$ java
@RestController
@RequestMapping("/multiple-instance")
public class MultipleInstanceController {
    @Value("${server.port}")
    private String port;
    @GetMapping("/ping")
    public ResponseEntity<String> ping() {
        return ResponseEntity.ok("Instance is up and running on port " + port);
    }
}

最后,启动这两个 IntelliJ 配置,让它们分别在各自的端口上运行: [LOADING...]

此时,我们应该拥有两个运行在不同端口上的相同应用程序实例。让我们通过向每个端口发送简单的 curl ping 请求来确认:

$ bash
apelanovic@Aleksandars-MacBook-Pro spring-boot-runtime-2 % curl localhost:8081/multiple-instance/ping
Instance is up and running on port 8081%
apelanovic@Aleksandars-MacBook-Pro spring-boot-runtime-2 % curl localhost:8082/multiple-instance/ping
Instance is up and running on port 8082%

3. 使用 Spring Profiles

虽然命令行参数适用于简单场景,但 Spring Profiles 提供了一种更结构化的管理多个实例的方法。

Spring Profiles 允许我们将配置属性分组,并在运行时根据需要激活它们。 我们无需直接将端口作为参数传递,而是可以定义特定于 Profile 的配置文件。为此,我们在 src/main/resources 下创建两个属性文件:

$ bash
application-instance1.properties
application-instance2.properties

现在,我们可以在每个文件中分配不同的端口,例如 server.port=8083server.port=8084

之后,我们像之前一样创建两个 IntelliJ 配置。这次,我们不再指定 --server.port,而是激活一个特定的 Profile。这可以通过参数或虚拟机选项(VM options)来实现,两者都能启用选定的 Profile。

在本例中,我们将使用 VM 选项: [LOADING...]

运行后,日志确认应用程序正在使用选定的 Profile 并在指定端口上运行:

2026-02-27T20:40:23,695 INFO  [main] o.s.b.SpringApplication: The following 1 profile is active: "instance1"
2026-02-27T20:40:24,426 INFO  [main] o.s.b.w.e.t.TomcatWebServer: Tomcat initialized with port 8083 (http)

为确保一切正常,可以像之前一样通过向每个端口发送 curl 请求来检查应用程序:

$ bash
apelanovic@Aleksandars-MacBook-Pro spring-boot-runtime-2 % curl localhost:8083/multiple-instance/ping
Instance is up and running on port 8083%
apelanovic@Aleksandars-MacBook-Pro spring-boot-runtime-2 % curl localhost:8084/multiple-instance/ping
Instance is up and running on port 8084%

4. 结论

在本文中,我们探讨了在 IntelliJ IDEA 中运行多个 Spring Boot 实例的两种简单方法。

当只需更改少量属性(如服务器端口)时,使用命令行参数是一种快速且直接的解决方案。另一方面,当实例需要更复杂的配置差异时,Spring Profiles 提供了一种更强大的方法。

一如既往,完整的代码示例可在 GitHub 上获取。