練習 - 建立 Quarkus 應用程式
在此單元中,您會建立基本的 Quarkus 應用程式。 您可以使用 Maven 來啟動應用程式,以及您選擇的整合開發環境 (IDE) 來編輯程式代碼。 使用前置條件中設定的 Bash 環境來執行程式碼。 您可以使用 Docker 來啟動本機 PostgreSQL 資料庫,讓您可以在本機執行及測試應用程式。
使用 Maven 產生 Quarkus 應用程式
有數種方式可以產生 Quarkus 項目結構。 您可以使用 Quarkus Web 介面、IDE 外掛程式或 Quarkus Maven 外掛程式。 讓我們使用 Maven 外掛程式來產生項目結構。
您會產生具有數個相依性的應用程式:
- 要公開 REST 端點的
resteasy相依性 - 用於序列化和反序列化 JSON 的
jackson依賴性 - 要與資料庫互動的
hibernate相依性 - 要連線到 PostgreSQL 資料庫的
postgresql相依性 - 要建置 Docker 映射的
quarkus-container-image-docker相依性
您不需要指定 Azure 相依性,因為您必須先在本機執行應用程式,然後將其容器化版本部署到 Azure 容器應用程式。
備註
本模組中的指令使用 Bash 語法。 不要把它們原封不動地貼到 PowerShell 或 Windows 命令提示字元。 在 Windows 上,請在已設定的 WSL 發行版中執行 Bash 指令。 在應用程式執行時,使用另一個本地的 Bash 終端機來處理 HTTP 請求。
在產生專案前,請確認你的 Bash 環境是否使用 Java 17 和 Maven 3.9.9:
java -version
mvn --version
初始產生器指令使用你安裝的 Maven。 專案的 Maven 包裝器是在之後建立的,因此不會取代這個前置條件。 在繼續之前,請先選擇所需的 Java 和 Maven 版本。
從你想建立專案的目錄中,產生 to-do 應用程式:
mvn -U io.quarkus:quarkus-maven-plugin:3.19.0:create \
-DplatformVersion=3.18.4 \
-DprojectGroupId=com.example.demo \
-DprojectArtifactId=todo \
-DclassName="com.example.demo.TodoResource" \
-Dpath="/api/todos" \
-DjavaVersion=17 \
-Dextensions="resteasy-jackson, hibernate-orm-panache, jdbc-postgresql, io.quarkus:quarkus-container-image-docker"
此指令會在名為 todo的目錄中建立一個新的 Quarkus 專案。 它會產生 Maven 目錄結構 (src/main/java 用於原始程式碼,而 src/test/java 用於測試)。 它會建立一些 Java 類別、一些測試,以及一些 Dockerfiles。 它也會產生具有所有所需相依性的 pom.xml 檔案(Hibernate、RESTEasy、Jackson、PostgreSQL 和 Docker):
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-container-image-docker</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
備註
pom.xml 檔案中的所有相依性都會定義在 Quarkus BOM(材料帳單)io.quarkus.platform:quarkus-bom中。
撰寫應用程式程序代碼
接下來,將產生的 MyEntity.java 類別重新命名為 Todo.java(位於與 TodoResource.java 檔案相同的資料夾中)。 以下列 Java 程式代碼取代現有的程式代碼。 它會使用 Java Persistence API (jakarta.persistence.* 套件)從 PostgreSQL 伺服器儲存和擷取數據。 它也使用Hibernate ORM 搭配 Panache(繼承自io.quarkus.hibernate.orm.panache.PanacheEntity),以簡化資料持久層。
您可以使用 JPA 實體 (@Entity) 將 Java Todo 物件直接對應至 PostgreSQL Todo 資料表。
TodoResource REST 端點接著會建立新的 Todo 實體類別,並加以保存。 這個類別是在 Todo 資料表上對應的網域模型。 JPA 會自動建立數據表。
擴充 PanacheEntity 可讓您取得您類型的一些泛型建立、讀取、更新和刪除 (CRUD) 方法。 因此,您可以在一行 Java 程式代碼中儲存和刪除 Todo 物件等動作。
將下列程式代碼新增至 Todo 實體:
package com.example.demo;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.persistence.Entity;
import java.time.Instant;
@Entity
public class Todo extends PanacheEntity {
public String description;
public String details;
public boolean done;
public Instant createdAt = Instant.now();
@Override
public String toString() {
return "Todo{" +
"id=" + id + '\'' +
", description='" + description + '\'' +
", details='" + details + '\'' +
", done=" + done +
", createdAt=" + createdAt +
'}';
}
}
若要管理該類別,請更新 TodoResource,以便發行 REST 介面以使用 HTTP 儲存和擷取數據。 開啟 TodoResource 類別,並以下列程式碼進行取代:
package com.example.demo;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.util.List;
@Path("/api/todos")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public class TodoResource {
@Inject
Logger logger;
@Inject
UriInfo uriInfo;
@POST
@Transactional
public Response createTodo(Todo todo) {
logger.info("Creating todo: " + todo);
Todo.persist(todo);
UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder().path(todo.id.toString());
return Response.created(uriBuilder.build()).entity(todo).build();
}
@GET
public List<Todo> getTodos() {
logger.info("Getting all todos");
return Todo.listAll();
}
@GET
@Path("/{id}")
public Todo getTodo(@PathParam("id") Long id) {
Todo todo = id == null ? null : Todo.findById(id);
if (todo == null) {
throw new NotFoundException();
}
return todo;
}
}
POST 方法會在 Location 標頭中回傳新項目的 URI。 item GET 方法會處理該 URI,若找不到該項目則回傳 HTTP 404。 null 防護也會處理 RESTEasy 轉換為 null 識別碼的路徑值,而不會將 null 傳遞給 Panache。
執行應用程式
當您在開發模式中執行應用程式時,Docker 必須執行。 這是因為 Quarkus 偵測到您需要 PostgreSQL 資料庫(因為 postgreSQL 相依性 quarkus-jdbc-postgresql 在 pom.xml 檔案中宣告),下載 PostgreSQL Docker 映射,並使用資料庫啟動容器。 然後,它會自動在資料庫中建立 Todo 數據表。
備註
固定版本的 Quarkus 3.18.4 平台使用 Testcontainers 1.20.4,其 Java Docker 用戶端預設為 API 1.32。
Docker Engine 29.x 現在預設不再接受該 API 版本。 如果你用的是 Engine 29.x,請執行 docker version 並確認伺服器支援的 API 範圍是否包含 1.44。 只有在確實如此時,才在啟動 Quarkus 或測試前於此 Bash shell 中執行以下指令:
export JDK_JAVA_OPTIONS="${JDK_JAVA_OPTIONS:+$JDK_JAVA_OPTIONS }-Dapi.version=1.44"
測試和後續套件命令都要將此設定保留在同一個殼層中。
JDK_JAVA_OPTIONS 向 Java 啟動器流程提供 Java 系統屬性,且不變更已釘選的 Quarkus 版本。 單靠設定DOCKER_API_VERSION並不足以設定此版本的 Java Docker 用戶端。 不要強制在支援範圍排除 API 1.44 的伺服器上;改用經過獨立驗證、相容的 Docker 與用戶端設定。
確保 Docker 正在執行,且可從你設定的 Bash 環境存取。 在你產生專案的終端機中,進入 todo 目錄並啟動應用程式:
cd todo
./mvnw quarkus:dev
從這個產生的 todo 目錄執行所有後續的 Maven 指令。
Quarkus 應用程式應該會啟動並連線到您的資料庫。 您應該會看到下列輸出:
2025-02-28 08:38:33,418 INFO [io.qua.dat.dep.dev.DevServicesDatasourceProcessor] (build-28) Dev Services for default datasource (postgresql) started - container ID is ce37977203b0
2025-02-28 08:38:33,421 INFO [io.qua.hib.orm.dep.dev.HibernateOrmDevServicesProcessor] (build-6) Setting quarkus.hibernate-orm.database.generation=drop-and-create to initialize Dev Services managed database
__ ____ __ _____ ___ __ ____ ______
--/ __ \/ / / / _ | / _ \/ //_/ / / / __/
-/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2025-02-28 08:38:35,278 INFO [io.quarkus] (Quarkus Main Thread) todo 1.0.0-SNAPSHOT on JVM (powered by Quarkus 3.18.4) started in 5.367s. Listening on: http://localhost:8080
2025-02-28 08:38:35,280 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
2025-02-28 08:38:35,280 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [agroal, cdi, hibernate-orm, hibernate-orm-panache, jdbc-postgresql, narayana-jta, resteasy, resteasy-jackson, smallrye-context-propagation, vertx]
--
Tests paused
Press [e] to edit command line args (currently ''), [r] to resume testing, [o] Toggle test output, [:] for the terminal, [h] for more options>
若要測試應用程式,您可以使用 cURL。
在第二個本地 Bash 終端機中,使用以下指令在資料庫中建立一個新的 to-do 項目。 您應該會在 Quarkus 控制台中看到記錄:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"description":"Take Quarkus MS Learn","details":"Take the MS Learn on deploying Quarkus to Azure Container Apps","done": "true"}' \
http://127.0.0.1:8080/api/todos
此命令應該會傳回已建立的項目(並附有識別碼):
{"id":1,"description":"Take Quarkus MS Learn","details":"Take the MS Learn on deploying Quarkus to Azure Container Apps","done":true,"createdAt":"2025-02-26T07:27:30.093447Z"}
使用下列 cURL 命令建立第二個 to-do:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"description":"Take Azure Container Apps MS Learn","details":"Take the ACA Learn module","done": "false"}' \
http://127.0.0.1:8080/api/todos
接下來,使用新的 cURL 要求擷取數據:
curl http://127.0.0.1:8080/api/todos
此指令會回傳 to-do 項目清單,包括你所建立的項目。 每個項目還包括 createdAt;以下範例為簡潔起見省略了這些時間戳:
[
{"id":1,"description":"Take Quarkus MS Learn","details":"Take the MS Learn on deploying Quarkus to Azure Container Apps","done":true},
{"id":2,"description":"Take Azure Container Apps MS Learn","details":"Take the ACA Learn module","done":false}
]
測試應用程式
HTTP 檢查後,回到執行 Quarkus 的終端機,按 Ctrl+C 停止開發模式。 保持這個 Bash 殼層開啟,並停留在測試命令所在的todo目錄中。
若要測試應用程式,您可以使用現有的 TodoResourceTest 類別。 它必須測試 REST 端點。 若要測試端點,它會使用 RESTAssured。 測試會保留收集檢查,依循 POST 傳回的Location,並檢查遺失及無效的項目識別碼。 使用下列程式代碼取代 TodoResourceTest 類別中的程式代碼:
package com.example.demo;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import static jakarta.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
@QuarkusTest
class TodoResourceTest {
@Test
void shouldGetAllTodos() {
given()
.when().get("/api/todos")
.then()
.statusCode(200);
}
@Test
void shouldCreateATodo() {
Todo todo = new Todo();
todo.description = "Take Quarkus MS Learn";
todo.details = "Take the MS Learn on deploying Quarkus to Azure Container Apps";
todo.done = true;
Response created = given().body(todo)
.header(CONTENT_TYPE, APPLICATION_JSON)
.when().post("/api/todos")
.then()
.statusCode(201)
.extract().response();
String location = created.getHeader("Location");
assertNotNull(location);
long createdId = created.jsonPath().getLong("id");
Response retrieved = given()
.when().get(location)
.then()
.statusCode(200)
.extract().response();
assertEquals(createdId, retrieved.jsonPath().getLong("id"));
assertEquals(todo.description, retrieved.jsonPath().getString("description"));
}
@Test
void shouldReturnNotFoundForMissingTodo() {
given()
.when().get("/api/todos/-1")
.then().statusCode(404);
}
@Test
void shouldRejectInvalidTodoIds() {
given()
.when().get("/api/todos/not-a-number")
.then().statusCode(404);
given().urlEncodingEnabled(false)
.when().get("/api/todos/%20")
.then().statusCode(404);
}
}
Create 測試會從 POST 回應中讀取產生的識別碼,並將兩個識別碼作為 long 值進行比較。 invalid-identifier 測試會停用 %20 的自動 URL 編碼,使請求包含刻意編碼的空格。
當你測試應用程式時,Docker 必須正在執行,且可從同一個 Bash 環境存取,因為 Quarkus 會啟動一個獨立的 PostgreSQL 開發服務來進行測試。 在你停止 Quarkus 的終端機中,請使用以下指令測試應用程式:
./mvnw clean test
您應該會看到如下所示的輸出:
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.TodoResourceTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
保持這個 Bash shell 開啟,方便進行資料庫練習。 你會在那裡設定 AZ_POSTGRES_JDBC_URL、AZ_POSTGRES_USERNAME 和 AZ_POSTGRES_PASSWORD,然後在該 shell 中重新啟動 Quarkus。 在稍後的./mvnw clean package和部署步驟之前, ,用 Ctrl+C 停止遠端開發流程。 保留變數,不要在各單元之間重複設定資源名稱和密碼。
一個過程在 開始時會繼承其環境。 在另一個終端機匯出變數並不會更新已經執行中的 Quarkus 程序。 編輯application.properties和依賴即時重新載入並不足以切換到 Azure;請從您設定變數的殼層重新啟動應用程式。