spring boot 3 的 Controller 必須寫成響應式的嗎? 是否可以依然像 spring boot 2 那樣寫傳統的 Controller

gongchengship發表於2024-07-05

在 Spring Boot 3 中,你仍然可以像在 Spring Boot 2 中一樣編寫傳統的基於 Servlet 的同步 Controller。響應式程式設計是可選的,而不是強制的。Spring Boot 3 繼續支援基於 Spring MVC 的傳統程式設計模型,同時也提供對響應式程式設計(如 WebFlux)的支援。

### 傳統同步 Controller 示例

這是一個傳統的基於 Spring MVC 的同步 Controller 示例,它在 Spring Boot 2 和 Spring Boot 3 中都可以使用:

```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

@GetMapping("/hello/{name}")
public String sayHello(@PathVariable String name) {
return "Hello, " + name + "!";
}
}
```

### 響應式 Controller 示例

如果你希望使用響應式程式設計,可以使用 Spring WebFlux。這是一個使用 Spring WebFlux 的響應式 Controller 示例:

```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class MyReactiveController {

@GetMapping("/hello/{name}")
public Mono<String> sayHello(@PathVariable String name) {
return Mono.just("Hello, " + name + "!");
}
}
```

### 選擇適合的程式設計模型

- **傳統同步程式設計模型(Spring MVC)**:適合處理 I/O 密集型的任務,比如處理短時間的請求-響應週期,傳統的資料庫操作等。它使用 Servlet API,所有請求處理都是同步的。

- **響應式程式設計模型(Spring WebFlux)**:適合處理高併發和非阻塞的任務,比如實時資料流處理,長時間的連線等。它基於 Reactive Streams API,所有請求處理都是非同步和非阻塞的。

### 在 Spring Boot 3 中使用傳統程式設計模型

你可以繼續使用傳統的 Spring MVC 程式設計模型而不需要遷移到響應式程式設計模型。Spring Boot 3 中的 Spring MVC 和 WebFlux 可以共存,你可以根據需求選擇合適的程式設計模型。

### 配置示例

在 `pom.xml` 中,確保你引入了適當的依賴:

```xml
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring WebFlux (可選) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
```

在 Spring Boot 3 中使用傳統的同步程式設計模型時,你無需進行額外的配置,只需確保正確的依賴項和配置檔案即可。

總結來說,Spring Boot 3 並不強制要求使用響應式程式設計,你可以繼續使用傳統的 Spring MVC 程式設計模型。如果你的專案目前使用的是同步 Controller,並且你不打算遷移到響應式程式設計,那麼你可以在 Spring Boot 3 中保持現狀,繼續使用傳統的同步 Controller。

相關文章