练习 - 创建 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"
此命令在名为 的目录中创建新的 Quarkus 项目。 它生成 Maven 目录结构(源代码src/main/java 和测试 src/test/java)。 它创建一些 Java 类、一些测试和一些 Dockerfiles。 它还会生成具有所有所需依赖项(Hibernate、RESTEasy、Jackson、PostgreSQL 和 Docker)的 pom.xml 文件:
<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 持久性 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,可以获得一些针对你的类型的通用 create、read、update 和 delete (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。 项 GET 方法提供该 URI,如果未找到该项,则返回 HTTP 404。 null 防护还处理 RESTEasy 转换为 null 标识符的路径值,而不将 null 传递给 Panache。
运行应用程序
在开发模式下运行应用程序时,Docker 需要运行。 这是因为 Quarkus 检测到您需要 PostgreSQL 数据库(由于在 quarkus-jdbc-postgresql 文件中声明了 PostgreSQL 依赖项 ),然后下载 PostgreSQL Docker 映像,并启动带有数据库的容器。 然后,它会自动在数据库中创建 Todo 表。
注释
固定的 Quarkus 3.18.4 平台使用 Testcontainers 1.20.4,其Java Docker 客户端默认为 API 1.32。
Docker Engine 29.x 默认不再接受该 API 版本。 如果使用引擎 29.x,请运行 docker version 并确认服务器支持的 API 范围包括 1.44。 仅在满足该条件时,请在启动 Quarkus 或运行测试之前,在此 Bash shell 中运行以下命令:
export JDK_JAVA_OPTIONS="${JDK_JAVA_OPTIONS:+$JDK_JAVA_OPTIONS }-Dapi.version=1.44"
将此设置保留在用于测试和后续打包命令的同一 shell 中。
JDK_JAVA_OPTIONS为 Java 启动器进程提供 Java 系统属性,而无需更改固定的 Quarkus 版本。 仅设置 DOCKER_API_VERSION 并不能完成对此版本 Java Docker 客户端的配置。 不要在其支持范围不包括 API 1.44 的服务器上强制使用 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 shell 保持打开状态,并停留在 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);
}
}
创建测试从 POST 响应中读取生成的标识符,并将这两个标识符作为 long 值进行比较。 无效标识符测试禁用 %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 窗口打开,以便进行数据库练习。 你将在该 shell 中设置 AZ_POSTGRES_JDBC_URL、AZ_POSTGRES_USERNAME 和 AZ_POSTGRES_PASSWORD,然后从该 shell 重启 Quarkus。 在执行稍后的 ./mvnw clean package 和部署步骤之前,请先按 Ctrl+C 停止远程开发过程。 保留变量,不要在单元之间重复资源名称和密码设置。
进程 在启动时继承其环境。 在另一个终端中导出变量不会更新已运行的 Quarkus 进程。 编辑 application.properties 并依赖实时重载,并不能切换到 Azure;请从设置这些变量的 shell 中重启应用程序。