├── LICENSE ├── README.md └── article-service ├── .gitignore ├── .tool-versions ├── README.md ├── app ├── build.gradle └── src │ ├── main │ ├── java │ │ └── dev │ │ │ └── huhao │ │ │ └── example │ │ │ └── realworld │ │ │ └── articleservice │ │ │ └── Application.java │ └── resources │ │ └── application.yml │ └── test │ ├── java │ ├── dev │ │ └── huhao │ │ │ └── example │ │ │ └── realworld │ │ │ └── articleservice │ │ │ └── KarateTestController.java │ ├── features │ │ ├── KarateRunnerBase.java │ │ ├── articles │ │ │ ├── ArticlesRunner.java │ │ │ ├── article-get.feature │ │ │ └── articles-post.feature │ │ └── db-restore.feature │ └── karate-config.js │ └── resources │ └── application.yml ├── build.gradle ├── docker-compose.yml ├── domain ├── build.gradle └── src │ ├── main │ ├── java │ │ └── dev │ │ │ └── huhao │ │ │ └── example │ │ │ └── realworld │ │ │ └── articleservice │ │ │ ├── model │ │ │ └── Article.java │ │ │ ├── repository │ │ │ └── ArticleRepository.java │ │ │ └── service │ │ │ ├── ArticleService.java │ │ │ └── exception │ │ │ ├── ArticleExistedException.java │ │ │ └── ArticleNotFoundException.java │ └── resources │ │ ├── application.yml │ │ └── db │ │ └── migration │ │ └── V20210224114725__create_article_table.sql │ └── test │ ├── java │ └── dev │ │ └── huhao │ │ └── example │ │ └── realworld │ │ └── articleservice │ │ ├── repository │ │ ├── ArticleRepositoryTest.java │ │ └── RepositoryTestBase.java │ │ └── service │ │ ├── ArticleServiceTest.java │ │ └── ServiceTestBase.java │ └── resources │ └── application.yml ├── gateway ├── build.gradle └── src │ ├── main │ └── resources │ │ └── application.yml │ └── test │ └── resources │ └── application.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── protocol ├── build.gradle └── src │ ├── main │ ├── java │ │ └── dev │ │ │ └── huhao │ │ │ └── example │ │ │ └── realworld │ │ │ └── articleservice │ │ │ └── protocol │ │ │ └── controller │ │ │ ├── ArticleController.java │ │ │ └── request │ │ │ └── ArticleCreateRequest.java │ └── resources │ │ └── application.yml │ └── test │ ├── java │ └── dev │ │ └── huhao │ │ └── example │ │ └── realworld │ │ └── articleservice │ │ └── protocol │ │ └── controller │ │ ├── ArticleControllerTest.java │ │ └── ControllerTestBase.java │ └── resources │ └── application.yml └── settings.gradle /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Hao Hu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Implementation Patterns Example for Spring Boot 2 | -------------------------------------------------------------------------------- /article-service/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | app/target/ 8 | 9 | ### STS ### 10 | .apt_generated 11 | .classpath 12 | .factorypath 13 | .project 14 | .settings 15 | .springBeans 16 | .sts4-cache 17 | bin/ 18 | !**/src/main/**/bin/ 19 | !**/src/test/**/bin/ 20 | 21 | ### IntelliJ IDEA ### 22 | .idea 23 | *.iws 24 | *.iml 25 | *.ipr 26 | out/ 27 | !**/src/main/**/out/ 28 | !**/src/test/**/out/ 29 | 30 | ### NetBeans ### 31 | /nbproject/private/ 32 | /nbbuild/ 33 | /dist/ 34 | /nbdist/ 35 | /.nb-gradle/ 36 | 37 | ### VS Code ### 38 | .vscode/ 39 | -------------------------------------------------------------------------------- /article-service/.tool-versions: -------------------------------------------------------------------------------- 1 | java adoptopenjdk-17.0.4+101 2 | gradle 7.3.1 3 | -------------------------------------------------------------------------------- /article-service/README.md: -------------------------------------------------------------------------------- 1 | # RealWorld - Article Service 2 | 3 | ## 实现模式(Implementation Patterns) 4 | 5 | ### 组件:Service / Model / Repository 6 | 7 | - 工序#1(30 min):Stub Repository,实现 Service 组装 Model 8 | - 工序#2(15 min):Stub / Mock Repository,实现 Service 抛出自定义 RuntimeException 9 | - 工序#3(30 min):Fake DB,编写 Migration,增加 Model 的 Spring Data JPA 注解,实现 Repository 对 Model 进行持久化操作,填充审计字段 10 | - 工序#4(5 min):对 Service 的数据写入类方法增加 org.springframework.transaction.annotation.Transactional 注解实现事务 11 | - 工序#8(5 min):对 Service 的数据只读类方法增加 org.springframework.transaction.annotation.Transactional(readonly = true) 注解实现只读事务 12 | 13 | ### 组件:Controller / Request 14 | 15 | - 工序#5(30 min):Fake Http Request,Stub Service,在 Controller 实现指定 API(HttpMethod + URI)和响应结果(Status Code, Response 16 | Body) 17 | - 工序#6(15 min):Fake Http Request,Stub Service 抛出异常,在 Controller 实现相应 API 的异常处理,抛出 ResponseStatusException 以返回对应的异常(Status Code、Message) 18 | 19 | ### API 功能测试 20 | 21 | - 工序#7(15 min):添加 API 功能测试。 22 | 23 | ## 任务分解(Tasking) 24 | 25 | ### Story#1:作为作者,我想要创建文章,以便将文章发布到线上,并能分享访问地址。 26 | 27 | #### AC#1:通过 `POST /articles` 创建文章,当文章创建成功后,需要能够获得根据 title 自动生成的含 slug 的文章地址,以及文章信息。 28 | 29 | ##### Example#1:成功创建 30 | 31 | 1. 工序#1(30 min):Stub ArticleRepository,实现 ArticleService 组装 Article Model(拥有 slug、title、description、body、authorId、createdAt、updatedAt,其中 createdAt、updatedAt 无需赋值),基于 title 生成 slug。当 ArticleRepository 传入组装的 Article 后返回 Stub Article。 32 | 2. 工序#4(5 min):对上一步实现的 ArticleService 方法增加 org.springframework.transaction.annotation.Transactional 注解实现事务。 33 | 3. 工序#3(30 min):Fake DB,编写 Migration 创建 article 表,增加 Article 的 Spring Data JPA 注解,实现 ArticleRepository 创建 Article,并自动填充审计字段(createdAt、updatedAt)。 34 | 4. 工序#5(30 min):Stub ArticleService 返回 Stub Article。Fake Http Request 发送请求 `POST /articles { title, description, body, authorId }`。实现 ArticleController,验证响应为 `201 Created { slug、title、description、body、createdAt、updatedAt }`。 35 | 5. 工序#7(15 min):对上一步实现的 API 添加功能测试。 36 | 37 | #### AC#2: 当存在相同 slug 的文章时,不可创建文章,并提示:`the article with slug {slug} already exists` 38 | 39 | ##### Example#1:相同 slug 已存在 40 | 41 | 1. 工序#2(15 min):Stub ArticleRepository,返回 slug 已存在,实现 ArticleService 抛出 ArticleExistedException,message 为 `the article with slug {slug} already exists`,Mock ArticleRepository 验证未执行 save。 42 | 2. 工序#6(15 min):Stub ArticleService 抛出 ArticleExistedException。Fake Http Request 发送请求 `POST /articles { title, description, body, authorId }`。实现 ArticleController 捕获并抛出 ResponseStatusException。验证响应为 `409 Conflict`,Body 中的 message 为 `the article with slug {slug} already exists`。 43 | 3. 工序#7(15 min):对上一步实现的 API 添加功能测试。 44 | 45 | ### Story#2:作为用户,我想要通过 slug 获取文章,以便阅读。 46 | 47 | #### AC#1:当使用 `/articles/{slug}` 访问文章的时候,能够获取文章信息 48 | 49 | ##### Example#1:给定的 slug 存在,成功获取文章 50 | 51 | 1. 工序#1(30 min):Stub ArticleRepository。实现 ArticleService 根据 slug 返回 Article。当 ArticleRepository 传入 slug 后返回 Stub Article。 52 | 2. 工序#8(5 min):对上一步实现的 ArticleService 方法增加 org.springframework.transaction.annotation.Transactional(readonly = true) 注解实现只读事务。 53 | 3. 工序#3(30 min):Fake DB,实现 ArticleRepository 根据 slug 获取 Article。 54 | 4. 工序#5(30 min):Stub ArticleService 返回 Stub Article。Fake Http Request 发送请求 `GET /articles/{slug}`。实现 ArticleController,验证响应为 `200 Ok { slug、title、description、body、createdAt、updatedAt }`。 55 | 5. 工序#7(15 min):对上一步实现的 API 添加功能测试。 56 | 57 | #### AC#2:当 slug 不存在的时候,需要告知:`cannot find the article with slug {slug}` 58 | 59 | ##### Example#1:给定的 slug 不存在 60 | 61 | 1. 工序#2(15 min):Stub ArticleRepository,返回 Empty,实现 ArticleService 抛出 ArticleNotFoundException,message 为 `cannot find the article with slug {slug}`。 62 | 2. 工序#6(15 min):Stub ArticleService 抛出 ArticleNotFoundException。Fake Http Request 发送请求 `GET /articles/{slug}`。实现 ArticleController 捕获并抛出 ResponseStatusException。验证响应为 `404 Not Found`,Body 中的 message 为 `cannot find the article with slug {slug}`。 63 | 3. 工序#7(15 min):对上一步实现的 API 添加功能测试。 64 | -------------------------------------------------------------------------------- /article-service/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.7.4' 3 | } 4 | 5 | dependencies { 6 | // Gradle Module 可被用作描述和实现分层架构及依赖关系 7 | implementation project(':protocol') 8 | implementation project(':domain') 9 | implementation project(':gateway') 10 | 11 | implementation 'org.springframework.boot:spring-boot-starter' 12 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 13 | // 此处引入 Spring Data Jpa 为了在 Application 级别启用事务管理 @EnableTransactionManagement 14 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 15 | // 利用 Spring Boot DevTools 优化开发环境的开发调试 16 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 17 | 18 | // 测试环境引入 Flyway 配合 Spring Data Jpa 实现测试环境下的数据库 Schema 自动迁移和重置 19 | testImplementation 'org.flywaydb:flyway-core' 20 | // 由于 API 功能测试环境启动了 Servlet 并使用了 MySql,丧失了Spring Data Jpa 的数据库自动重置和事务回滚能力 21 | // 所以使用 Flyway Test 扩展来实现测试时的数据库迁移和重置 22 | testImplementation 'org.flywaydb.flyway-test-extensions:flyway-spring-test:7.0.0' 23 | 24 | // 使用 Karate 实现更加面向 Living Document 的单服务 API 功能测试 25 | testImplementation 'com.intuit.karate:karate-junit5:1.4.0' 26 | // 用于在测试时通过 RESTful API 提供测试专用功能 27 | testImplementation 'org.springframework.boot:spring-boot-starter-web' 28 | } 29 | 30 | test { 31 | useJUnitPlatform() 32 | // pull karate options into the runtime 33 | systemProperty "karate.options", System.properties.getProperty("karate.options") 34 | // pull karate env into the runtime 35 | systemProperty "karate.env", System.properties.getProperty("karate.env") 36 | // ensure tests are always run 37 | outputs.upToDateWhen { false } 38 | } 39 | 40 | sourceSets { 41 | test { 42 | resources { 43 | srcDir file('src/test/java') 44 | exclude '**/*.java' 45 | } 46 | } 47 | } 48 | 49 | task karateDebug(type: JavaExec) { 50 | classpath = sourceSets.test.runtimeClasspath 51 | mainClass.set('com.intuit.karate.cli.Main') 52 | } 53 | -------------------------------------------------------------------------------- /article-service/app/src/main/java/dev/huhao/example/realworld/articleservice/Application.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 6 | import org.springframework.transaction.annotation.EnableTransactionManagement; 7 | 8 | @SpringBootApplication 9 | // 开启事务管理才能使 @Transactional 注解有效 10 | @EnableTransactionManagement 11 | // 开启 Spring Data JPA 的审计功能 12 | @EnableJpaAuditing 13 | public class Application { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(Application.class, args); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /article-service/app/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | # 设置 MySql 数据库用于开发环境,需要启动 docker-compose 以便使用 MySql 容器 4 | driver-class-name: com.mysql.cj.jdbc.Driver 5 | url: jdbc:mysql://localhost:3306/article_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false 6 | username: root 7 | password: password 8 | server: 9 | error: 10 | # 永远显示异常响应中的 message 信息(默认为 Never)用作自定义异常原因解释的存放和展示 11 | include-message: always 12 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/dev/huhao/example/realworld/articleservice/KarateTestController.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice; 2 | 3 | import org.flywaydb.core.Flyway; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseStatus; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | // 仅用于在测试时通过 RESTful API 提供测试专用功能 11 | @RestController 12 | @RequestMapping("/karate-tests") 13 | public class KarateTestController { 14 | 15 | private final Flyway flyway; 16 | 17 | public KarateTestController(Flyway flyway) { 18 | 19 | this.flyway = flyway; 20 | } 21 | 22 | @PostMapping("/db-restoration") 23 | @ResponseStatus(HttpStatus.OK) 24 | public void resetDb() { 25 | flyway.clean(); 26 | flyway.migrate(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/features/KarateRunnerBase.java: -------------------------------------------------------------------------------- 1 | package features; 2 | 3 | import dev.huhao.example.realworld.articleservice.Application; 4 | import org.flywaydb.test.FlywayTestExecutionListener; 5 | import org.flywaydb.test.annotation.FlywayTest; 6 | import org.springframework.beans.factory.InitializingBean; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | import org.springframework.test.context.TestExecutionListeners; 11 | import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; 12 | 13 | // 启用完整服务并提供随机端口,指定 Application 作为 Spring Boot 上下文的入口 14 | @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 15 | // 使用 https://github.com/flyway/flyway-test-extensions 来实现每个测试类重置数据库 16 | // 测试过程中的数据库重置依靠自定义 Karate 的 Feature 显式调用便于优化测试设计和降低 API 功能测试的数据重置成本 17 | @FlywayTest 18 | /* 使用 flyway-test-extensions 的配置要求,由于覆盖了默认的 @TestExecutionListeners 配置, 19 | 所以需要显式加入 DependencyInjectionTestExecutionListener.class,默认配置请看 @TestExecutionListeners 的实现*/ 20 | @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, FlywayTestExecutionListener.class}) 21 | public abstract class KarateRunnerBase implements InitializingBean { 22 | 23 | // 注入随机端口 24 | @Value("${local.server.port}") 25 | int port; 26 | 27 | @Override 28 | public void afterPropertiesSet() { 29 | // 通过系统属性将随机端口提供给 Karate 调用 30 | System.setProperty("local.server.port", String.valueOf(port)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/features/articles/ArticlesRunner.java: -------------------------------------------------------------------------------- 1 | package features.articles; 2 | 3 | import com.intuit.karate.junit5.Karate; 4 | import features.KarateRunnerBase; 5 | 6 | public class ArticlesRunner extends KarateRunnerBase { 7 | @Karate.Test 8 | Karate testAll() { 9 | return Karate.run().relativeTo(getClass()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/features/articles/article-get.feature: -------------------------------------------------------------------------------- 1 | Feature: get article api 2 | 3 | Background: 4 | * url localUrl 5 | * def articleBase = '/articles' 6 | 7 | Scenario: article not found 8 | Given path `${articleBase}/fake-slug` 9 | When method get 10 | Then status 404 11 | And header Content-Type = 'application/json' 12 | And match $.message == 'cannot find the article with slug fake-slug' 13 | 14 | Scenario: get a exist article 15 | * def result = call read('articles-post.feature@create') 16 | 17 | Given path `${articleBase}/${result.response.slug}` 18 | When method get 19 | Then status 200 20 | And header Content-Type = 'application/json' 21 | And match $.slug == 'fake-title' 22 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/features/articles/articles-post.feature: -------------------------------------------------------------------------------- 1 | Feature: create article api 2 | 3 | Background: 4 | * url localUrl 5 | * def articleBase = '/articles' 6 | * def randomUUID = function(){ return java.util.UUID.randomUUID() + '' } 7 | * def authorId = callonce randomUUID 8 | 9 | @create 10 | Scenario: create an article 11 | # 重置数据库 12 | * call read(dbRestoreFeature) 13 | 14 | Given path articleBase 15 | And request 16 | """ 17 | { 18 | title: 'Fake Title', 19 | description: 'Description', 20 | body: 'Something', 21 | authorId: '#(authorId)' 22 | } 23 | """ 24 | And header Accept = 'application/json' 25 | When method post 26 | Then status 201 27 | And header Content-Type = 'application/json' 28 | And match response == 29 | """ 30 | { 31 | slug: 'fake-title', 32 | title: 'Fake Title', 33 | description: 'Description', 34 | body: 'Something', 35 | authorId: '#(authorId)', 36 | createdAt: '#notnull', 37 | updatedAt: '#notnull' 38 | } 39 | """ 40 | 41 | Scenario: slug conflict 42 | Given path articleBase 43 | And request 44 | """ 45 | { 46 | title: 'Fake Title', 47 | description: 'Description', 48 | body: 'Something', 49 | authorId: '#(authorId)' 50 | } 51 | """ 52 | And header Accept = 'application/json' 53 | When method post 54 | Then status 409 55 | And match header Content-Type == 'application/json' 56 | And match $.message == 'the article with slug fake-title already exists' 57 | 58 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/features/db-restore.feature: -------------------------------------------------------------------------------- 1 | @ignore 2 | Feature: As a tester, I would like to restore database, so that I can isolate the test scenarios easily. 3 | 4 | Background: 5 | * url localUrl 6 | 7 | Scenario: call db restoration api 8 | Given path '/karate-tests/db-restoration' 9 | When method post 10 | Then status 200 11 | -------------------------------------------------------------------------------- /article-service/app/src/test/java/karate-config.js: -------------------------------------------------------------------------------- 1 | // Karate 配置文件 2 | function fn() { 3 | 4 | // 通过系统属性获取 SpringBootTest 注入的随机端口(需配合 KarateRunnerBase 中的设置代码) 5 | const port = karate.properties['local.server.port']; 6 | 7 | // 设置 Karate 配置的全局变量供 feature 文件调用 8 | const config = { 9 | localUrl: 'http://localhost:' + port, 10 | dbRestoreFeature: 'classpath:features/db-restore.feature' 11 | }; 12 | 13 | // 设置连接和读取超时时间 14 | karate.configure('connectTimeout', 5000); 15 | karate.configure('readTimeout', 5000); 16 | 17 | return config; 18 | } 19 | -------------------------------------------------------------------------------- /article-service/app/src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | # 设置 MySql 数据库用于 API 功能测试环境,需要启动 docker-compose 以便使用 MySql 容器 4 | driver-class-name: com.mysql.cj.jdbc.Driver 5 | url: jdbc:mysql://localhost:3307/article_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false 6 | username: root 7 | password: password 8 | server: 9 | error: 10 | # 永远显示异常响应中的 message 信息(默认为 Never)用作自定义异常原因解释的存放和展示 11 | include-message: always 12 | -------------------------------------------------------------------------------- /article-service/build.gradle: -------------------------------------------------------------------------------- 1 | // 本工程的 Gradle 多 Module 实现参考此文章:https://reflectoring.io/spring-boot-gradle-multi-module/ 2 | 3 | plugins { 4 | id 'io.spring.dependency-management' version '1.0.14.RELEASE' 5 | } 6 | 7 | subprojects { 8 | group = 'dev.huhao.example.realworld' 9 | version = '0.0.1' 10 | 11 | apply plugin: 'java' 12 | apply plugin: 'io.spring.dependency-management' 13 | apply plugin: 'java-library' 14 | 15 | sourceCompatibility = JavaVersion.VERSION_17 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | dependencyManagement { 22 | imports { 23 | mavenBom('org.springframework.boot:spring-boot-dependencies:2.7.4') 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /article-service/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | 5 | db: 6 | image: mysql 7 | command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci 8 | restart: always 9 | environment: 10 | MYSQL_DATABASE: article_db 11 | MYSQL_ROOT_PASSWORD: password 12 | ports: 13 | - 3306:3306 14 | 15 | db_api_test: 16 | image: mysql 17 | command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci 18 | restart: always 19 | environment: 20 | MYSQL_DATABASE: article_db 21 | MYSQL_ROOT_PASSWORD: password 22 | ports: 23 | - 3307:3306 24 | # 利用 tmpfs 实现内存读写,加速测试时的 MySql 访问,但会消耗更多内存 25 | tmpfs: 26 | - /var/lib/mysql 27 | -------------------------------------------------------------------------------- /article-service/domain/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | // 使用 Flyway 的 Gradle 插件支持 Gradle Task 的使用 3 | id "org.flywaydb.flyway" version "8.5.13" 4 | } 5 | 6 | dependencies { 7 | // Gradle Module 可被用作描述和实现分层架构及依赖关系 8 | implementation project(':gateway') 9 | 10 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 11 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 12 | 13 | // 非测试环境使用 MySql 作为真实数据库 14 | runtimeOnly 'mysql:mysql-connector-java' 15 | runtimeOnly 'org.flywaydb:flyway-mysql' 16 | 17 | // 测试环境通过 H2 内存型数据库实现 Fake MySql 18 | testRuntimeOnly 'com.h2database:h2' 19 | // 测试环境引入 Flyway 配合 Spring Data Jpa 实现测试环境下的数据库 Schema 自动迁移和重置 20 | testImplementation 'org.flywaydb:flyway-core' 21 | 22 | // 第三方库用于生成 slug 23 | implementation 'com.github.slugify:slugify:3.0.2' 24 | } 25 | 26 | test { 27 | useJUnitPlatform() 28 | } 29 | 30 | // 通过 Gradle Task 实现通过 CLI 可控执行非测试环境的数据库 Schema 迁移 31 | flyway { 32 | url = 'jdbc:mysql://localhost:3306/article_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false' 33 | user = 'root' 34 | password = 'password' 35 | locations = ['classpath:db/migration'] 36 | } 37 | -------------------------------------------------------------------------------- /article-service/domain/src/main/java/dev/huhao/example/realworld/articleservice/model/Article.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.model; 2 | 3 | import org.springframework.data.annotation.CreatedDate; 4 | import org.springframework.data.annotation.LastModifiedDate; 5 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.EntityListeners; 10 | import javax.persistence.Id; 11 | import java.time.Instant; 12 | import java.util.UUID; 13 | 14 | @Entity 15 | // 开启 Spring Data JPA 的审计监听功能 16 | @EntityListeners(AuditingEntityListener.class) 17 | public class Article { 18 | @Id 19 | private String slug; 20 | 21 | @Column(nullable = false) 22 | private String title; 23 | 24 | private String description; 25 | private String body; 26 | 27 | @Column(nullable = false) 28 | private UUID authorId; 29 | 30 | @Column(nullable = false, updatable = false) 31 | @CreatedDate 32 | private Instant createdAt; 33 | 34 | @Column(nullable = false) 35 | @LastModifiedDate 36 | private Instant updatedAt; 37 | 38 | public String getSlug() { 39 | return slug; 40 | } 41 | 42 | public void setSlug(String slug) { 43 | this.slug = slug; 44 | } 45 | 46 | public String getTitle() { 47 | return title; 48 | } 49 | 50 | public void setTitle(String title) { 51 | this.title = title; 52 | } 53 | 54 | public String getDescription() { 55 | return description; 56 | } 57 | 58 | public void setDescription(String description) { 59 | this.description = description; 60 | } 61 | 62 | public String getBody() { 63 | return body; 64 | } 65 | 66 | public void setBody(String body) { 67 | this.body = body; 68 | } 69 | 70 | public UUID getAuthorId() { 71 | return authorId; 72 | } 73 | 74 | public void setAuthorId(UUID authorId) { 75 | this.authorId = authorId; 76 | } 77 | 78 | public Instant getCreatedAt() { 79 | return createdAt; 80 | } 81 | 82 | public void setCreatedAt(Instant createdAt) { 83 | this.createdAt = createdAt; 84 | } 85 | 86 | public Instant getUpdatedAt() { 87 | return updatedAt; 88 | } 89 | 90 | public void setUpdatedAt(Instant updatedAt) { 91 | this.updatedAt = updatedAt; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /article-service/domain/src/main/java/dev/huhao/example/realworld/articleservice/repository/ArticleRepository.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.repository; 2 | 3 | import dev.huhao.example.realworld.articleservice.model.Article; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ArticleRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /article-service/domain/src/main/java/dev/huhao/example/realworld/articleservice/service/ArticleService.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.service; 2 | 3 | import com.github.slugify.Slugify; 4 | import dev.huhao.example.realworld.articleservice.model.Article; 5 | import dev.huhao.example.realworld.articleservice.repository.ArticleRepository; 6 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleExistedException; 7 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleNotFoundException; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.UUID; 12 | 13 | @Service 14 | public class ArticleService { 15 | 16 | private final ArticleRepository articleRepository; 17 | 18 | public ArticleService(ArticleRepository articleRepository) { 19 | this.articleRepository = articleRepository; 20 | } 21 | 22 | @Transactional 23 | public Article createArticle(String title, String description, String body, UUID authorId) { 24 | var slug = Slugify.builder().build().slugify(title); 25 | 26 | if (articleRepository.existsById(slug)) { 27 | throw new ArticleExistedException(slug); 28 | } 29 | 30 | var article = new Article(); 31 | article.setSlug(slug); 32 | article.setTitle(title); 33 | article.setDescription(description); 34 | article.setBody(body); 35 | article.setAuthorId(authorId); 36 | 37 | return articleRepository.save(article); 38 | } 39 | 40 | @Transactional(readOnly = true) 41 | public Article getArticle(String slug) { 42 | return articleRepository.findById(slug).orElseThrow(() -> new ArticleNotFoundException(slug)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /article-service/domain/src/main/java/dev/huhao/example/realworld/articleservice/service/exception/ArticleExistedException.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.service.exception; 2 | 3 | public class ArticleExistedException extends RuntimeException { 4 | public ArticleExistedException(String slug) { 5 | super(String.format("the article with slug %s already exists", slug)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /article-service/domain/src/main/java/dev/huhao/example/realworld/articleservice/service/exception/ArticleNotFoundException.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.service.exception; 2 | 3 | public class ArticleNotFoundException extends RuntimeException { 4 | public ArticleNotFoundException(String slug) { 5 | super(String.format("cannot find the article with slug %s", slug)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /article-service/domain/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/domain/src/main/resources/application.yml -------------------------------------------------------------------------------- /article-service/domain/src/main/resources/db/migration/V20210224114725__create_article_table.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `article` 2 | ( 3 | `slug` VARCHAR(60) PRIMARY KEY, 4 | `title` VARCHAR(60) NOT NULL, 5 | `description` VARCHAR(160), 6 | `body` TEXT, 7 | -- UUID 类型必须保存成为 BINARY(16),否则 Spring Data JPA 会在 MySql 环境下报错,类似: 8 | -- java.sql.SQLException: Incorrect string value: '\x9Bra\x9A\xC22...' 9 | -- 这也是一个 H2 与 MySql 的差异,如果用 H2 作为 Fake DB,则可以使用 CHAR(36) 那么就会有潜在的不一致风险 10 | -- 另一方面,UUID 保存为 BINARY(16),也能获得更好的性能:https://www.singlestore.com/forum/t/best-uuid-data-type/182 11 | `author_id` BINARY(16) NOT NULL, 12 | `created_at` TIMESTAMP(6) NOT NULL, 13 | `updated_at` TIMESTAMP(6) NOT NULL 14 | ) 15 | -------------------------------------------------------------------------------- /article-service/domain/src/test/java/dev/huhao/example/realworld/articleservice/repository/ArticleRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.repository; 2 | 3 | import dev.huhao.example.realworld.articleservice.model.Article; 4 | import org.junit.jupiter.api.Nested; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 8 | 9 | import java.time.Instant; 10 | import java.util.UUID; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | public class ArticleRepositoryTest extends RepositoryTestBase { 15 | 16 | @Autowired 17 | private TestEntityManager entityManager; 18 | 19 | @Autowired 20 | private ArticleRepository articleRepository; 21 | 22 | @Nested 23 | class save { 24 | 25 | @Test 26 | void should_create_article_when_not_exist() { 27 | // Given 28 | var newArticle = new Article(); 29 | newArticle.setSlug("fake-title"); 30 | newArticle.setTitle("Fake Title"); 31 | newArticle.setDescription("Description"); 32 | newArticle.setBody("Something"); 33 | var authorId = UUID.randomUUID(); 34 | newArticle.setAuthorId(authorId); 35 | 36 | // When 37 | var result = articleRepository.save(newArticle); 38 | 39 | // Then 40 | assertThat(result.getSlug()).isEqualTo("fake-title"); 41 | assertThat(result.getTitle()).isEqualTo("Fake Title"); 42 | assertThat(result.getDescription()).isEqualTo("Description"); 43 | assertThat(result.getBody()).isEqualTo("Something"); 44 | assertThat(result.getAuthorId()).isEqualTo(authorId); 45 | assertThat(result.getCreatedAt()).isNotNull(); 46 | assertThat(result.getUpdatedAt()).isNotNull(); 47 | } 48 | } 49 | 50 | @Nested 51 | class findById { 52 | 53 | @Test 54 | void should_find_article_by_slug() { 55 | // Given 56 | var existingArticle = new Article(); 57 | existingArticle.setSlug("fake-title"); 58 | existingArticle.setTitle("Fake Title"); 59 | existingArticle.setDescription("Description"); 60 | existingArticle.setBody("Something"); 61 | existingArticle.setCreatedAt(Instant.now()); 62 | existingArticle.setUpdatedAt(Instant.now()); 63 | existingArticle.setAuthorId(UUID.randomUUID()); 64 | 65 | entityManager.persist(existingArticle); 66 | entityManager.flush(); 67 | 68 | // When 69 | var result = articleRepository.findById(existingArticle.getSlug()); 70 | 71 | // Then 72 | assertThat(result) 73 | .hasValueSatisfying(v -> assertThat(v).usingRecursiveComparison().isEqualTo(existingArticle)); 74 | } 75 | 76 | @Test 77 | void should_be_empty_when_no_existing_data() { 78 | // When 79 | var result = articleRepository.findById(""); 80 | 81 | // Then 82 | assertThat(result).isEmpty(); 83 | } 84 | 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /article-service/domain/src/test/java/dev/huhao/example/realworld/articleservice/repository/RepositoryTestBase.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.repository; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.autoconfigure.domain.EntityScan; 5 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 6 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 7 | 8 | // 由于只测试从 Repository 到数据库的分层边界集成情况, 9 | // 所以使用 @DataJpaTest 而不是 @SpringBootTest 来减少上下文复杂度,同时利用其所提供的测试工具降低测试成本 10 | @DataJpaTest 11 | public abstract class RepositoryTestBase { 12 | 13 | // 多 Gradle Module 情况下对于没用 @SpringBootApplication 的 Module 需要在测试时现实声明以加载 Spring Boot 上下文 14 | @SpringBootApplication 15 | // 在测试中必须显式声明 @Entity 所标记的 JPA 实体所在包路径,否则无法自动注入 16 | @EntityScan(basePackages = {"dev.huhao.example.realworld.articleservice.model"}) 17 | // 开启 Spring Data JPA 的审计功能 18 | @EnableJpaAuditing 19 | static class TestConfiguration { 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /article-service/domain/src/test/java/dev/huhao/example/realworld/articleservice/service/ArticleServiceTest.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.service; 2 | 3 | import dev.huhao.example.realworld.articleservice.model.Article; 4 | import dev.huhao.example.realworld.articleservice.repository.ArticleRepository; 5 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleExistedException; 6 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleNotFoundException; 7 | import org.junit.jupiter.api.Nested; 8 | import org.junit.jupiter.api.Test; 9 | import org.mockito.ArgumentCaptor; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.mock.mockito.MockBean; 12 | 13 | import java.util.Optional; 14 | import java.util.UUID; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 18 | import static org.mockito.ArgumentMatchers.any; 19 | import static org.mockito.BDDMockito.given; 20 | import static org.mockito.BDDMockito.then; 21 | import static org.mockito.Mockito.mock; 22 | import static org.mockito.Mockito.never; 23 | 24 | public class ArticleServiceTest extends ServiceTestBase { 25 | 26 | @MockBean 27 | private ArticleRepository articleRepository; 28 | 29 | @Autowired 30 | private ArticleService articleService; 31 | 32 | @Nested 33 | class TestCreateArticle { 34 | 35 | @Test 36 | void should_create_article() { 37 | // Given 38 | var stubArticle = new Article(); 39 | var spyArticle = ArgumentCaptor.forClass(Article.class); 40 | var authorId = UUID.randomUUID(); 41 | given(articleRepository.save(spyArticle.capture())).willReturn(stubArticle); 42 | 43 | // When 44 | var result = articleService.createArticle("Fake Title", "Description", "Something", authorId); 45 | 46 | // Then 47 | assertThat(result).isEqualTo(stubArticle); 48 | assertThat(spyArticle.getValue().getSlug()).isEqualTo("fake-title"); 49 | assertThat(spyArticle.getValue().getTitle()).isEqualTo("Fake Title"); 50 | assertThat(spyArticle.getValue().getDescription()).isEqualTo("Description"); 51 | assertThat(spyArticle.getValue().getBody()).isEqualTo("Something"); 52 | assertThat(spyArticle.getValue().getAuthorId()).isEqualTo(authorId); 53 | } 54 | 55 | @Test 56 | void should_throw_ArticleExistedException_with_message_when_slug_existed() { 57 | // Given 58 | given(articleRepository.existsById(any())).willReturn(true); 59 | 60 | // Then 61 | assertThatThrownBy(() -> 62 | // When 63 | articleService.createArticle("Fake Title", "", "", UUID.randomUUID()) 64 | ) 65 | .isInstanceOf(ArticleExistedException.class) 66 | .hasMessage("the article with slug fake-title already exists"); 67 | 68 | then(articleRepository).should(never()).save(any()); 69 | } 70 | } 71 | 72 | @Nested 73 | class TestGetArticle { 74 | 75 | @Test 76 | void should_get_article() { 77 | // Given 78 | var slug = "fake-slug"; 79 | var stubArticle = mock(Article.class); 80 | given(articleRepository.findById(slug)).willReturn(Optional.of(stubArticle)); 81 | 82 | // When 83 | var result = articleService.getArticle(slug); 84 | 85 | // Then 86 | assertThat(result).isEqualTo(stubArticle); 87 | } 88 | 89 | @Test 90 | void should_throw_ArticleNotFoundException_with_message_when_not_found() { 91 | // Given 92 | given(articleRepository.findById(any())).willReturn(Optional.empty()); 93 | 94 | // Then 95 | assertThatThrownBy(() -> 96 | // When 97 | articleService.getArticle("fake-slug") 98 | ).isInstanceOf(ArticleNotFoundException.class).hasMessage("cannot find the article with slug fake-slug"); 99 | } 100 | 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /article-service/domain/src/test/java/dev/huhao/example/realworld/articleservice/service/ServiceTestBase.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.service; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | @SpringBootTest 10 | public abstract class ServiceTestBase { 11 | 12 | // 多 Gradle Module 情况下对于没用 @SpringBootApplication 的 Module 需要在测试时现实声明以加载 Spring Boot 上下文 13 | // 由于对 Service 层进行单元测试 Stub 掉了 Repository,所以需要禁用 Spring Data Jpa 的相关自动配置功能 14 | @SpringBootApplication(exclude = { 15 | DataSourceAutoConfiguration.class, 16 | DataSourceTransactionManagerAutoConfiguration.class, 17 | HibernateJpaAutoConfiguration.class 18 | }) 19 | static class TestConfiguration { 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /article-service/domain/src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | # 设置 H2 内存型数据库用于测试环境 4 | driver-class-name: org.h2.Driver 5 | # MODE=MySQL 用于兼容 MySQL 6 | # DATABASE_TO_UPPER=false 用于关闭 H2 默认生成大写表名的功能,避免 Flyway 因大小写问题找不到所生成的数据表而报错 7 | url: jdbc:h2:mem:test;MODE=MySQL;DATABASE_TO_UPPER=false 8 | username: sa 9 | password: sa 10 | -------------------------------------------------------------------------------- /article-service/gateway/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/gateway/build.gradle -------------------------------------------------------------------------------- /article-service/gateway/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/gateway/src/main/resources/application.yml -------------------------------------------------------------------------------- /article-service/gateway/src/test/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/gateway/src/test/resources/application.yml -------------------------------------------------------------------------------- /article-service/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /article-service/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /article-service/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /article-service/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /article-service/protocol/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | // Gradle Module 可被用作描述和实现分层架构及依赖关系 3 | implementation project(':domain') 4 | 5 | implementation 'org.springframework.boot:spring-boot-starter-web' 6 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 7 | } 8 | 9 | test { 10 | useJUnitPlatform() 11 | } 12 | -------------------------------------------------------------------------------- /article-service/protocol/src/main/java/dev/huhao/example/realworld/articleservice/protocol/controller/ArticleController.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.protocol.controller; 2 | 3 | import dev.huhao.example.realworld.articleservice.model.Article; 4 | import dev.huhao.example.realworld.articleservice.protocol.controller.request.ArticleCreateRequest; 5 | import dev.huhao.example.realworld.articleservice.service.ArticleService; 6 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleExistedException; 7 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleNotFoundException; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | import org.springframework.web.server.ResponseStatusException; 11 | import org.springframework.web.util.UriComponentsBuilder; 12 | 13 | import static org.springframework.http.HttpStatus.CONFLICT; 14 | import static org.springframework.http.HttpStatus.NOT_FOUND; 15 | import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; 16 | import static org.springframework.http.ResponseEntity.created; 17 | 18 | @RestController 19 | @RequestMapping(value = "/articles", produces = APPLICATION_JSON_VALUE) 20 | public class ArticleController { 21 | 22 | private final ArticleService articleService; 23 | 24 | public ArticleController(ArticleService articleService) { 25 | this.articleService = articleService; 26 | } 27 | 28 | @PostMapping(consumes = APPLICATION_JSON_VALUE) 29 | public ResponseEntity create(@RequestBody ArticleCreateRequest data, UriComponentsBuilder uriComponentsBuilder) { 30 | try { 31 | var article = articleService.createArticle(data.title(), data.description(), data.body(), data.authorId()); 32 | var uriComponents = uriComponentsBuilder.path("/articles/{slug}").buildAndExpand(article.getSlug()); 33 | return created(uriComponents.toUri()).body(article); 34 | } catch (ArticleExistedException ex) { 35 | throw new ResponseStatusException(CONFLICT, ex.getMessage()); 36 | } 37 | } 38 | 39 | @GetMapping(value = "/{slug}") 40 | public Article get(@PathVariable String slug) { 41 | try { 42 | return articleService.getArticle(slug); 43 | } catch (ArticleNotFoundException ex) { 44 | throw new ResponseStatusException(NOT_FOUND, ex.getMessage()); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /article-service/protocol/src/main/java/dev/huhao/example/realworld/articleservice/protocol/controller/request/ArticleCreateRequest.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.protocol.controller.request; 2 | 3 | import java.util.UUID; 4 | 5 | public record ArticleCreateRequest(String title, String description, String body, UUID authorId) { 6 | } 7 | -------------------------------------------------------------------------------- /article-service/protocol/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/protocol/src/main/resources/application.yml -------------------------------------------------------------------------------- /article-service/protocol/src/test/java/dev/huhao/example/realworld/articleservice/protocol/controller/ArticleControllerTest.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.protocol.controller; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import dev.huhao.example.realworld.articleservice.model.Article; 5 | import dev.huhao.example.realworld.articleservice.protocol.controller.request.ArticleCreateRequest; 6 | import dev.huhao.example.realworld.articleservice.service.ArticleService; 7 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleExistedException; 8 | import dev.huhao.example.realworld.articleservice.service.exception.ArticleNotFoundException; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Nested; 11 | import org.junit.jupiter.api.Test; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.test.mock.mockito.MockBean; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | 16 | import java.time.Instant; 17 | import java.util.UUID; 18 | 19 | import static org.hamcrest.Matchers.containsString; 20 | import static org.hamcrest.Matchers.is; 21 | import static org.mockito.ArgumentMatchers.any; 22 | import static org.mockito.BDDMockito.given; 23 | import static org.springframework.http.MediaType.APPLICATION_JSON; 24 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 25 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 26 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 27 | 28 | public class ArticleControllerTest extends ControllerTestBase { 29 | 30 | @Autowired 31 | private MockMvc mvc; 32 | 33 | @Autowired 34 | private ObjectMapper objectMapper; 35 | 36 | @MockBean 37 | private ArticleService articleService; 38 | 39 | @Nested 40 | @DisplayName("POST /articles") 41 | class TestCreateArticle { 42 | 43 | @Test 44 | void should_create_article() throws Exception { 45 | // Given 46 | var authorId = UUID.randomUUID(); 47 | 48 | var request = new ArticleCreateRequest("Fake Title", "Description", "Something", authorId); 49 | 50 | var stubArticle = new Article(); 51 | stubArticle.setSlug("fake-title"); 52 | stubArticle.setTitle(request.title()); 53 | stubArticle.setDescription(request.description()); 54 | stubArticle.setBody(request.body()); 55 | stubArticle.setCreatedAt(Instant.now()); 56 | stubArticle.setUpdatedAt(Instant.now()); 57 | stubArticle.setAuthorId(authorId); 58 | 59 | given(articleService.createArticle("Fake Title", "Description", "Something", authorId)) 60 | .willReturn(stubArticle); 61 | 62 | // When 63 | mvc.perform(post("/articles") 64 | .content(objectMapper.writeValueAsString(request)) 65 | .accept(APPLICATION_JSON).contentType(APPLICATION_JSON)) 66 | 67 | // Then 68 | .andExpect(status().isCreated()) 69 | .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) 70 | .andExpect(header().string("Location", containsString("/articles/" + stubArticle.getSlug()))) 71 | .andExpect(jsonPath("$.slug", is(stubArticle.getSlug()))) 72 | .andExpect(jsonPath("$.title", is(stubArticle.getTitle()))) 73 | .andExpect(jsonPath("$.description", is(stubArticle.getDescription()))) 74 | .andExpect(jsonPath("$.body", is(stubArticle.getBody()))) 75 | .andExpect(jsonPath("$.authorId", is(stubArticle.getAuthorId().toString()))) 76 | .andExpect(jsonPath("$.createdAt", is(stubArticle.getCreatedAt().toString()))) 77 | .andExpect(jsonPath("$.updatedAt", is(stubArticle.getUpdatedAt().toString()))); 78 | } 79 | 80 | @Test 81 | void should_409_conflict_with_message_when_slug_existed() throws Exception { 82 | //Given 83 | var request = new ArticleCreateRequest("Fake Title", "Description", "Something", UUID.randomUUID()); 84 | 85 | var exception = new ArticleExistedException("fake-slug"); 86 | given(articleService.createArticle(any(), any(), any(), any())).willThrow(exception); 87 | 88 | 89 | // When 90 | mvc.perform(post("/articles") 91 | .content(objectMapper.writeValueAsString(request)) 92 | .accept(APPLICATION_JSON).contentType(APPLICATION_JSON)) 93 | 94 | // Then 95 | .andExpect(status().isConflict()) 96 | .andExpect(status().reason(exception.getMessage())); 97 | } 98 | } 99 | 100 | @Nested 101 | @DisplayName("GET /articles/{slug}") 102 | class TestGetArticle { 103 | 104 | @Test 105 | void should_get_article() throws Exception { 106 | // Given 107 | var stubArticle = new Article(); 108 | stubArticle.setSlug("fake-title"); 109 | stubArticle.setTitle("Fake Title"); 110 | stubArticle.setDescription("Description"); 111 | stubArticle.setBody("Something"); 112 | stubArticle.setCreatedAt(Instant.now()); 113 | stubArticle.setUpdatedAt(Instant.now()); 114 | stubArticle.setAuthorId(UUID.randomUUID()); 115 | 116 | given(articleService.getArticle(stubArticle.getSlug())).willReturn(stubArticle); 117 | 118 | // When 119 | mvc.perform(get("/articles/" + stubArticle.getSlug()).accept(APPLICATION_JSON)) 120 | 121 | // Then 122 | .andExpect(status().isOk()) 123 | .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) 124 | .andExpect(jsonPath("$.slug", is(stubArticle.getSlug()))) 125 | .andExpect(jsonPath("$.title", is(stubArticle.getTitle()))) 126 | .andExpect(jsonPath("$.description", is(stubArticle.getDescription()))) 127 | .andExpect(jsonPath("$.body", is(stubArticle.getBody()))) 128 | .andExpect(jsonPath("$.authorId", is(stubArticle.getAuthorId().toString()))) 129 | .andExpect(jsonPath("$.createdAt", is(stubArticle.getCreatedAt().toString()))) 130 | .andExpect(jsonPath("$.updatedAt", is(stubArticle.getUpdatedAt().toString()))); 131 | 132 | } 133 | 134 | @Test 135 | void should_404_with_message_when_not_found() throws Exception { 136 | // Given 137 | var slug = "fake-slug"; 138 | var exception = new ArticleNotFoundException(slug); 139 | given(articleService.getArticle(any())).willThrow(exception); 140 | 141 | // When 142 | mvc.perform(get("/articles/" + slug) 143 | .accept(APPLICATION_JSON)) 144 | 145 | // Then 146 | .andExpect(status().isNotFound()) 147 | .andExpect(status().reason(exception.getMessage())); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /article-service/protocol/src/test/java/dev/huhao/example/realworld/articleservice/protocol/controller/ControllerTestBase.java: -------------------------------------------------------------------------------- 1 | package dev.huhao.example.realworld.articleservice.protocol.controller; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 5 | 6 | // 由于 SUT 为 Controller 层,所以需要 Fake Http Request 以及 Stub Service,来隔离和验证组件边界 7 | // 所以使用 @WebMvcTest 而不是 @SpringBootTest 来减少上下文复杂度,同时利用其所提供的测试工具降低测试成本 8 | @WebMvcTest 9 | public abstract class ControllerTestBase { 10 | 11 | // 多 Gradle Module 情况下对于没用 @SpringBootApplication 的 Module 需要在测试时现实声明以加载 Spring Boot 上下文 12 | @SpringBootApplication 13 | static class TestConfiguration { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /article-service/protocol/src/test/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howiehu/implementation-patterns-spring/3380904d3e368c603f458c987f025c6869b05905/article-service/protocol/src/test/resources/application.yml -------------------------------------------------------------------------------- /article-service/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'article-service' 2 | include 'app', 'protocol', 'domain', 'gateway' 3 | --------------------------------------------------------------------------------