1. 概述
在本文檔中,我們將討論 Spring 與 Vert.x 的集成,並充分利用兩者的優勢:成熟且廣為人知的 Spring 功能,以及 Vert.x 的反應式單事件循環。
為了更深入地瞭解 Vert.x,請參考我們的入門文章 [此處鏈接]。
2. 安裝準備
首先,讓我們確保依賴項已到位:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>3.9.15</version>
</dependency>請注意,我們已從 spring-boot-starter-web 中排除嵌入式 Tomcat 依賴,因為我們將使用 Verticles 部署我們的服務。
您可以在這裏找到最新的依賴項:這裏。
3. Spring Vert.x 應用程序
現在,我們將構建一個包含兩個部署的 Verticle 的示例應用程序。
第一個 Verticle 將請求路由到處理程序,該處理程序將它們作為消息發送到指定的地址。另一個 Verticle 在指定的地址上監聽。
讓我們看看它們在行動中的效果。
3.1. 發送方垂直組件 (Sender Verticle)
ServerVerticle 接收 HTTP 請求並將它們作為消息發送到指定的地址。 讓我們創建一個 ServerVerticle 類,該類繼承自 AbstractVerticle,並覆蓋 start() 方法以創建我們的 HTTP 服務器:
@Override
public void start() throws Exception {
super.start();
Router router = Router.router(vertx);
router.get("/api/baeldung/articles")
.handler(this::getAllArticlesHandler);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", 8080));
}在服務器請求處理程序中,我們傳遞了一個 router 對象,它會將任何傳入的請求重定向到 getAllArticlesHandler 處理程序:
private void getAllArticlesHandler(RoutingContext routingContext) {
vertx.eventBus().<String>send(ArticleRecipientVerticle.GET_ALL_ARTICLES, "",
result -> {
if (result.succeeded()) {
routingContext.response()
.putHeader("content-type", "application/json")
.setStatusCode(200)
.end(result.result()
.body());
} else {
routingContext.response()
.setStatusCode(500)
.end();
}
});
}在處理方法中,我們向 Vert.x Event bus 傳遞一個事件,事件 ID 為 GET_ALL_ARTICLES。然後,我們根據成功和錯誤場景對回調進行處理。
消息將由 ArticleRecipientVerticle 消費,該 Verticle 在下一部分進行討論。
3.2. 接收端垂直 (Recipient Verticle)
<em style="font-style: italic;">RecipientVerticle</em> 監聽傳入的消息,並注入一個 Spring Bean。它作為 Spring 和 Vert.x 的會話點。
我們將向 Verticle 注入 Spring 服務 Bean,並調用相應的函數:
@Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer(GET_ALL_ARTICLES)
.handler(getAllArticleService(articleService));
}
這裏,articleService 是一個注入的 Spring Bean。
@Autowired
private ArticleService articleService;
這個垂直組件將持續監聽事件總線,地址為 。收到消息後,它會將消息委託給 處理方法:
private Handler<Message<String>> getAllArticleService(ArticleService service) {
return msg -> vertx.<String> executeBlocking(future -> {
try {
future.complete(
mapper.writeValueAsString(service.getAllArticle()));
} catch (JsonProcessingException e) {
future.fail(e);
}
}, result -> {
if (result.succeeded()) {
msg.reply(result.result());
} else {
msg.reply(result.cause().toString());
}
});
}這段代碼執行所需的服務操作,並以包含狀態信息的回覆消息返回。該回復消息在 ServerVerticle 和回調中的 result 中被引用,正如我們在前面章節中看到的。
4. 服務類
服務類是一個簡單的實現,提供方法與存儲層進行交互:
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepository;
public List<Article> getAllArticle() {
return articleRepository.findAll();
}
}ArticleRepository 繼承了 org.springframework.data.repository.CrudRepository,並提供基本的 CRUD 功能。
5. 部署 Verticles
我們將按照常規 Spring Boot 應用程序的方式部署應用程序。我們需要創建一個 Vert.X 實例,並在 Spring 上下文初始化完成後部署 Verticles。
public class VertxSpringApplication {
@Autowired
private ServerVerticle serverVerticle;
@Autowired
private ArticleRecipientVerticle articleRecipientVerticle;
public static void main(String[] args) {
SpringApplication.run(VertxSpringApplication.class, args);
}
@PostConstruct
public void deployVerticle() {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(serverVerticle);
vertx.deployVerticle(articleRecipientVerticle);
}
}請注意,我們正在將垂直實例注入到 Spring 應用類中。因此,我們需要對 Verticle 類進行標註,
因此,我們需要對 Verticle 類進行標註,ServerVerticle和ArticleRecipientVerticle使用@Component。
讓我們測試應用程序:
@Test
public void givenUrl_whenReceivedArticles_thenSuccess() {
ResponseEntity<String> responseEntity = restTemplate
.getForEntity("http://localhost:8080/api/baeldung/articles", String.class);
assertEquals(200, responseEntity.getStatusCodeValue());
}6. 結論
在本文中,我們學習瞭如何使用 Spring 和 Vert.x 構建 RESTful WebService。