docker

在 Spring Boot 开发模式中使用 Testcontainers 和 Docker

在本文中,你将学习如何使用 Spring Boot 内置的 Testcontainers 和 Docker Compose 支持,在开发模式下运行外部服务。Spring Boot 在当前的最新版本 3.1 中引入了这些功能,你已经可以在 Spring Boot 应用的测试中利用 Testcontainers。在应用程序启动时运行外部数据库、message broker 或其他外部服务的功能是我一直期待的。尤其是竞争框架 Quarkus 已经提供了名为 Dev Services 的类似功能,这在我的开发过程中非常有用。此外,还有另一个令人兴奋的功能 - 与 Docker Compose 集成。 源代码 如果你想自己尝试,可以查看我的源代码。因为我经常使用 Testcontainers,所以你可以在我的多个仓库中找到示例。下面是我们今天要使用的仓库列表: https://github.com/piomin/sample-spring-boot-on-kubernetes.git https://github.com/piomin/sample-spring-microservices-advanced.git https://github.com/piomin/sample-spring-kafka-microservices.git 你可以克隆它们,然后按照指导查看如何在开发模式下使用 Spring Boot 内置的 Testcontainers 和 Docker Compose 支持。 在测试中使用 Testcontainers 让我们从标准使用示例开始。第一个仓库中有一个连接 Mongo 数据库的 Spring Boot 应用程序。为了构建自动测试,我们必须包含以下 Maven 依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>mongodb</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> 现在,我们可以创建测试了。我们需要用 @Testcontainers 来注解我们的测试类。然后,我们必须声明 MongoDBContainer Bean。在 Spring Boot 3.

Spring Boot 中内置的测试容器(Testcontainers)

1、概览 在本教程中,我们将讨论 Spring Boot 3.1 中引入的增强型 Testcontainers 支持。 这个更新提供了一种更简化的配置容器的方法,并允许我们启动它们进行本地开发。因此,使用 Testcontainers 进行开发和运行测试变得更加无缝和高效。 2、SpringBoot 3.1 之前的 Testcontainers 在测试阶段,我们可以使用 Testcontainers 创建一个类似生产的环境。这样,我们就不需要模拟,就能写出与实现细节无关的高质量自动测试。 在本文的代码示例中,我们将使用一个简单的 Web 应用程序,其中包含一个 MongoDB 数据库作为持久层,并具有一个小型的 REST 接口。 @RestController @RequestMapping("characters") public class MiddleEarthCharactersController { private final MiddleEarthCharactersRepository repository; // constructor not shown @GetMapping public List<MiddleEarthCharacter> findByRace(@RequestParam String race) { return repository.findAllByRace(race); } @PostMapping public MiddleEarthCharacter save(@RequestBody MiddleEarthCharacter character) { return repository.save(character); } } 在集成测试期间,我们将启动一个包含数据库服务器的 Docker 容器。由于容器暴露的数据库端口将动态分配,我们无法在 properties 文件中定义数据库 URL。因此,对于版本早于 3.1 的 Spring Boot 应用程序,我们需要使用 @DynamicPropertySource 注解才能将这些属性添加到 DynamicPropertyRegistry 中:

Spring Boot 3 中对 Docker Compose 的支持

1、概览 Spring Boot 3 具有一些新功能,比如将我们的应用程序构建为 GraalVM Native Image(原生镜像)。另一个相关支持是 Docker Compose。 在本教程中,我们将了解如何将 Docker Compose 工作流与 Spring Boot 3 整合。 2、Spring Boot 3 的 Docker Compose Support 提供了什么? 通常,我们会根据 docker-compose.yml 运行 docker-compose up 来启动和 docker-compose down 来停止我们的容器。现在,我们可以将这些 Docker Compose 命令委托给 Spring Boot 3。当 Spring Boot 应用程序启动或停止时,它也会管理我们的容器。 此外,它还内置了对多种服务的管理,如 SQL 数据库、MongoDB、Cassandra 等。因此,我们可能不需要在 application 资源文件中重复配置 class 或 properties。 最后,我们会看到如何在该支持中使用自定义 Docker 镜像和 Docker Compose profiles 。 3,设定 我们需要 Docker Compose 和 Spring Boot 3 来探索这种新的支持。 3.1、Docker Compose Docker Compose 需要已安装的 Docker 引擎。它们很容易安装,不过根据操作系统的不同可能会有差异。