返回

Spring Cloud 介绍

发布时间:2022-12-07 02:34:50 304
# less# json# git# 软件# 软件

Spring Cloud 介绍_spring

如果您正在开始使用Spring Cloud Contract或Spring,请从阅读开始 本节。它回答了基本的“什么?”,“如何?”和“为什么?”的问题。它 包括春云合约简介,以及安装说明。然后我们 引导您构建第一个 Spring 云合约应用程序,讨论一些核心 我们前进的原则。

1. 春云合约介绍

Spring Cloud Contract将TDD提升到软件架构层面。 它允许您执行消费者驱动和生产者驱动的合同测试。

1.1. 历史

在成为春云合约之前,这个项目被称为Accurest。 它由Marcin Grzejszczak和Jakub Kubrynski(Codearte)创建。

该版本于 2015 年 1 月 26 日发布,并于 2016 年 2 月 29 日发布后变得稳定。0.1.01.0.0

1.1.1. 你为什么需要它?

假设我们有一个由多个微服务组成的系统,如下所示 图片显示:

Spring Cloud 介绍_json_02

1.1.2. 测试问题

如果我们想在前面图片的左上角测试应用程序 部分来确定它是否可以与其他服务通信,我们可以做以下之一 两件事:

  • 部署所有微服务并执行端到端测试。
  • 在单元测试和集成测试中模拟其他微服务。

两者都有其优点,但也有很多缺点。

部署所有微服务并执行端到端测试

优势:

  • 模拟生产。
  • 测试服务之间的实际通信。

弊:

  • 要测试一个微服务,我们必须部署六个微服务,几个数据库, 和其他项目。
  • 运行测试的环境被锁定为单个测试套件(没有其他人 将能够同时运行测试)。
  • 它们需要很长时间才能运行。
  • 反馈在流程中很晚才出现。
  • 它们极难调试。

在单元测试和集成测试中模拟其他微服务

优势:

  • 他们提供非常快速的反馈。
  • 他们没有基础设施要求。

弊:

  • 服务的实现者创建可能与 现实。
  • 您可以通过测试和失败的生产进入生产环境。

为了解决上述问题,创建了春云合约。主要思想是 为您提供非常快速的反馈,无需设置 整个微服务世界。如果您处理存根,那么您唯一需要的应用程序 是应用程序直接使用的那些。下图显示了关系 应用程序的存根数:

Spring Cloud 介绍_spring_03

春云合约让您确定您使用的存根是 由您调用的服务创建。此外,如果您可以使用它们,则意味着它们 在制片人方面进行了测试。简而言之,您可以信任这些存根。

1.2. 目的

春云合约的主要目的是:

  • 确保 HTTP 和消息传递存根(在开发客户端时使用)完全正确执行 实际的服务器端实现的作用。
  • 推广ATDD(验收测试驱动开发)方法和微服务架构风格。
  • 提供一种方法来发布双方立即可见的合同更改。
  • 生成要在服务器端使用的样板测试代码。

默认情况下,Spring Cloud Contract 与Wiremock集成为 HTTP 服务器存根。

春云合约的目的不是开始写业务 合同中的功能。假设我们有一个欺诈检查的业务用例。如果 用户可能出于 100 种不同的原因进行欺诈,我们假设您会创建两个 合同,一个用于正面案例,一个用于负面案例。合同测试是 用于测试应用程序之间的协定,而不是模拟完整行为。

1.3. 什么是合同?

作为服务的消费者,我们需要定义我们到底想要实现什么。我们需要 制定我们的期望。这就是我们编写合同的原因。换句话说,合同是 关于 API 或消息通信外观的协议。请考虑以下示例:

假设您要发送一个请求,其中包含客户公司的 ID 和 它想向我们借款的金额。您还希望使用 方法。以下清单显示了一个合同,用于检查客户端是否应 在Groovy和YAML中都被标记为欺诈:​​/fraudcheck​​​​PUT​

/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package contracts

org.springframework.cloud.contract.spec.Contract.make {
request { // (1)
method 'PUT' // (2)
url '/fraudcheck' // (3)
body([ // (4)
"client.id": $(regex('[0-9]{10}')),
loanAmount : 99999
])
headers { // (5)
contentType('application/json')
}
}
response { // (6)
status OK() // (7)
body([ // (8)
fraudCheckStatus : "FRAUD",
"rejection.reason": "Amount too high"
])
headers { // (9)
contentType('application/json')
}
}
}

/*
From the Consumer perspective, when shooting a request in the integration test:

(1) - If the consumer sends a request
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the response will be sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` equal to `application/json`

From the Producer perspective, in the autogenerated producer-side test:

(1) - A request will be sent to the producer
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the test will assert if the response has been sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` matching `application/json.*`
*/

预计合同来自可信来源。切勿下载来自不受信任位置的合约或与之交互。

2. 三秒游

这个非常简短的教程将介绍使用春云合约。它由 以下主题:

  • 在生产者方面
  • 在消费者方面

你可以在这里找到更长的旅游。

下图显示了春云合约中各部分的关系:

Spring Cloud 介绍_应用程序_04

2.1. 在生产者方面

要开始使用 Spring Cloud 合约,您可以使用 REST 或消息合约添加文件 在 Groovy DSL 或 YAML 中表示到合约目录,该目录由属性设置。默认情况下,它是。​​contractsDslDir​​​​$rootDir/src/test/resources/contracts​

然后,您可以将 Spring Cloud 合同验证器依赖项和插件添加到构建文件中,如 以下示例显示:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<scope>test</scope>
</dependency>

以下清单显示了如何添加插件,该插件应包含在构建/插件中 部分文件:

<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
</plugin>

运行自动生成验证应用程序的测试 遵守添加的合同。默认情况下,测试在 下生成。​​./mvnw clean install​​​​org.springframework.cloud.contract.verifier.tests.​

由于合同中描述的功能尚未实现 存在,测试失败。

要使它们通过,您必须添加处理 HTTP 的正确实现 请求或消息。此外,还必须为自动生成的基测试类添加基测试类 对项目的测试。此类由所有自动生成的测试扩展,并且它 应包含运行它们所需的所有设置信息(例如控制器设置或消息传递测试设置)。​​RestAssuredMockMvc​

下面的示例 from 演示如何指定基测试类:​​pom.xml​

<build>
<plugins>
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>2.1.2.RELEASE</version>
<extensions>true</extensions>
<configuration>
<baseClassForTests>com.example.contractTest.BaseTestClass</baseClassForTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

该元素允许您指定基测试类。一定是个孩子

内在的元素。​​baseClassForTests​​​​configuration​​​​spring-cloud-contract-maven-plugin​

一旦实现和测试基类就位,测试就会通过,并且 应用程序和存根工件在本地 Maven 存储库中构建并安装。 现在可以合并更改,并且可以发布应用程序和存根项目 在联机存储库中。

2.2. 在消费者方面

您可以在集成测试中使用来运行 模拟实际服务的 WireMock 实例或消息传递路由。​​Spring Cloud Contract Stub Runner​

为此,请将依赖项添加到 以下示例显示:​​Spring Cloud Contract Stub Runner​

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency>

您可以在 Maven 存储库中安装生产者端存根,其中两个之一 方式:

  • 通过签出生产者端存储库并添加合约并生成存根 通过运行以下命令:
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests

测试被跳过,因为生产者端合约实现不是 尚未到位,因此自动生成的合约测试失败。

  • 通过从远程存储库获取已经存在的生产者服务存根。为此, 将存根项目 ID 和项目存储库 URL 作为属性传递,如以下示例所示:Spring Cloud Contract Stub Runner
stubrunner:
ids: 'com.example:http-server-dsl:+:stubs:8080'
repositoryRoot: https://repo.spring.io/libs-snapshot

现在,您可以使用来注释测试类。在注释中, 提供和值 为您运行协作者的存根,如以下示例所示:​​@AutoConfigureStubRunner​​​​group-id​​​​artifact-id​​​​Spring Cloud Contract Stub Runner​

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {
. . .
}

使用从在线存储库下载存根和离线工作时。​​REMOTE​​​​stubsMode​​​​LOCAL​

现在,在集成测试中,您可以接收 HTTP 响应的存根版本或 预期由协作者服务发出的消息。

3. 开发您的第一个基于 Spring Cloud 合同的应用程序

这个简短的教程将演练使用春云合约。它由以下主题组成:

  • 在生产者方面
  • 在消费者方面

您可以在此处找到更简短的游览。

为了这个例子,这是Nexus/Artifactory。​​Stub Storage​

下图显示了春云合约各部分的关系:

Spring Cloud 介绍_应用程序_05

3.1. 在生产者方面

要开始使用,您可以添加 Spring 云合同验证程序 构建文件的依赖项和插件,如以下示例所示:​​Spring Cloud Contract​

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<scope>test</scope>
</dependency>

以下清单显示了如何添加插件,该插件应包含在构建/插件中 部分文件:

<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
</plugin>

 

最简单的入门方法是转到Spring Initializr​并添加“Web”和“合约验证器”作为依赖项。这样做会拉入以前的 提到的依赖项以及文件中需要的所有其他内容(除了 设置基测试类,我们将在本节后面介绍)。下图 显示了要在Spring 初始化中使用的​设置:​​pom.xml​

 

 

Spring Cloud 介绍_json_06

 

现在,您可以添加带有消息传递合同的文件 在 Groovy DSL 或 YAML 中表示到合约目录,该目录由属性设置。默认情况下,它是。 请注意,文件名无关紧要。您可以在其中组织您的合同 具有您喜欢的任何命名方案的目录。​​REST/​​​​contractsDslDir​​​​$rootDir/src/test/resources/contracts​

对于 HTTP 存根,协定定义应为 给定请求(考虑 HTTP 方法、URL、标头、状态代码等 上)。以下示例显示了 Groovy 和 YAML 中的 HTTP 存根协定:

package contracts

org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/fraudcheck'
body([
"client.id": $(regex('[0-9]{10}')),
loanAmount: 99999
])
headers {
contentType('application/json')
}
}
response {
status OK()
body([
fraudCheckStatus: "FRAUD",
"rejection.reason": "Amount too high"
])
headers {
contentType('application/json')
}
}
}

如果需要使用消息传递,可以定义:

  • 输入和输出消息(考虑到它从哪里来 已发送、邮件正文和标头)。
  • 收到消息后应调用的方法。
  • 调用时应触发消息的方法。

以下示例显示了一个 Camel 消息传递协定:

def contractDsl = Contract.make {
name "foo"
label 'some_label'
input {
messageFrom('jms:delete')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
assertThat('bookWasDeleted()')
}
}

运行自动生成验证应用程序的测试 遵守添加的合同。默认情况下,生成的测试位于 下。​​./mvnw clean install​​​​org.springframework.cloud.contract.verifier.tests.​

生成的测试可能会有所不同,具体取决于您设置的框架和测试类型 在您的插件中。

在下一个列表中,您可以找到:

  • HTTP 协定的默认测试模式MockMvc
  • 具有测试模式的 JAX-RS 客户端JAXRS
  • 基于 A 的测试(在处理时特别推荐这样做) 基于反应式的应用程序)使用测试模式设置WebTestClientWeb-FluxWEBTESTCLIENT
  • 基于 Spock 的测试,其属性设置为testFrameworkSPOCK

您只需要其中一个测试框架。MockMvc 是默认值。使用一个 在其他框架中,将其库添加到类路径中。

以下清单显示了所有框架的示例:

模拟MVC

贾克斯

网络测试客户端

斯波克

@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");

// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}

由于合同中描述的功能尚未实现 存在,测试失败。

要使它们通过,您必须添加处理 HTTP 的正确实现 请求或消息。此外,还必须为自动生成的基测试类添加基测试类 对项目的测试。此类由所有自动生成的测试扩展,应 包含运行它们所需的所有设置必要信息(例如,控制器设置或消息传递测试设置)。​​RestAssuredMockMvc​

下面的示例 from 演示如何指定基测试类:​​pom.xml​




org.springframework.cloud
spring-cloud-contract-maven-plugin
2.1.2.RELEASE
true

com.example.contractTest.BaseTestClass



org.springframework.boot
spring-boot-maven-plugin


该元素允许您指定基测试类。一定是个孩子

内在的元素。​​baseClassForTests​​​​configuration​​​​spring-cloud-contract-maven-plugin​

下面的示例演示一个最小(但功能强大)的基测试类:

package com.example.contractTest;

import org.junit.Before;

import io.restassured.module.mockmvc.RestAssuredMockMvc;

public class BaseTestClass {

@Before
public void setup() {
RestAssuredMockMvc.standaloneSetup(new FraudController());
}
}

这个最小的类确实是你让测试工作所需要的。它作为一个 自动生成的测试附加到的起始位置。

现在我们可以继续实施。为此,我们首先需要一个数据类,我们 然后在我们的控制器中使用。下面的清单显示了数据类:

package com.example.Test;

import com.fasterxml.jackson.annotation.JsonProperty;

public class LoanRequest {

@JsonProperty("client.id")
private String clientId;

private Long loanAmount;

public String getClientId() {
return clientId;
}

public void setClientId(String clientId) {
this.clientId = clientId;
}

public Long getLoanAmount() {
return loanAmount;
}

public void setLoanRequestAmount(Long loanAmount) {
this.loanAmount = loanAmount;
}
}

前面的类提供了一个对象,我们可以在其中存储参数。因为 合约中的客户端 ID 被调用,我们需要使用参数将其映射到字段。​​client.id​​​​@JsonProperty("client.id")​​​​clientId​

现在我们可以转到控制器,以下列表显示:

package com.example.docTest;

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FraudController {

@PutMapping(value = "/fraudcheck", consumes="application/json", produces="application/json")
public String check(@RequestBody LoanRequest loanRequest) {

if (loanRequest.getLoanAmount() > 10000) {
return "{fraudCheckStatus: FRAUD, rejection.reason: Amount too high}";
} else {
return "{fraudCheckStatus: OK, acceptance.reason: Amount OK}";
}
}
}

我们将传入的参数映射到对象。​​LoanRequest​

我们检查要求的贷款金额,看看它是否太多。

如果太多,我们返回 JSON(此处使用简单字符串创建),该

测试预期。

如果我们有一个测试来捕获何时允许的数量,我们可以将其与此输出相匹配。

事情变得很简单。您可以做更多的事情,包括 日志记录、验证客户端 ID 等。​​FraudController​

一旦实现和测试基类就位,测试就会通过,并且 应用程序和存根工件在本地 Maven 存储库中构建并安装。 有关将存根 jar 安装到本地存储库的信息显示在日志中,如 以下示例显示:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

现在可以合并更改并发布应用程序和存根项目 在联机存储库中。

3.2. 在消费者方面

您可以在集成测试中使用 Spring Cloud 合约存根运行程序来运行 模拟实际服务的 WireMock 实例或消息传递路由。

若要开始,请将依赖项添加到,如下所示:​​Spring Cloud Contract Stub Runner​


org.springframework.cloud
spring-cloud-starter-contract-stub-runner
test

您可以在 Maven 存储库中安装生产者端存根,其中两个之一 方式:

  • 通过签出生产者端存储库并添加合约并生成 通过运行以下命令来存根:
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests

跳过测试,因为生产者端合约尚未实现 就地,因此自动生成的合约测试失败。

  • 通过从远程存储库获取现有的生产者服务存根。为此, 将存根项目 ID 和项目存储库 URL 作为属性传递,如以下示例所示:Spring Cloud Contract Stub Runner
stubrunner:
ids: 'com.example:http-server-dsl:+:stubs:8080'
repositoryRoot: https://repo.spring.io/libs-snapshot

现在,您可以使用来注释测试类。在注释中, 提供运行 协作者的存根,如以下示例所示:​​@AutoConfigureStubRunner​​​​group-id​​​​artifact-id​​​​Spring Cloud Contract Stub Runner​

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {
. . .
}

使用从在线存储库下载存根和离线工作时。​​REMOTE​​​​stubsMode​​​​LOCAL​

在集成测试中,您可以接收 HTTP 响应或消息的存根版本 预期由协作者服务发出。您可以看到类似的条目 到构建日志中的以下内容:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

4. 消费者驱动合同 (CDC) 分步指南,生产者方合同

考虑欺诈检测和贷款发放流程的示例。业务 场景是这样的,我们想向人们发放贷款,但不希望他们从中偷窃 安全信息我们系统目前实施的情况向所有人提供贷款。

假设这是服务器的客户端。在当前 Sprint,我们必须开发一个新功能:如果客户想借太多钱, 我们将客户标记为欺诈。​​Loan Issuance​​​​Fraud Detection​

技术备注

  • 欺诈检测具有反作用。artifact-idhttp-server
  • 贷款发行有反感。artifact-idhttp-client
  • 两者都有aof。group-idcom.example
  • 为了这个例子,这是Nexus/Artifactory。Stub Storage

社会评论

  • 客户端和服务器开发团队都需要直接通信和 在完成整个过程时讨论更改。
  • CDC是关于沟通的。

服务器端 代码可在此处获得,客户端代码可在此处获得。

在这种情况下,生产者拥有合同。从物理上讲,所有合同都是 在生产者的存储库中。

4.1. 技术说明

如果使用快照、里程碑或候选版本,则需要添加 以下部分:

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

为简单起见,我们使用以下首字母缩略词:

  • 贷款发行 (LI):HTTP 客户端
  • 欺诈检测 (FD):HTTP 服务器
  • SCC:春云合同

4.2. 消费者方(贷款发放)

作为贷款发放服务的开发人员(欺诈检测服务器的使用者),您可以执行以下步骤:

  1. 通过为您的功能编写测试来开始执行 TDD。
  2. 编写缺少的实现。
  3. 在本地克隆欺诈检测服务存储库。
  4. 在欺诈检测服务的存储库中本地定义合同。
  5. 添加 Spring Cloud Contract (SCC) 插件。
  6. 运行集成测试。
  7. 提交拉取请求。
  8. 创建初始实现。
  9. 接管拉取请求。
  10. 编写缺少的实现。
  11. 部署应用程序。
  12. 在线工作。

我们从贷款发行流程开始,以下UML图所示:

Spring Cloud 介绍_应用程序_07

4.2.1. 通过为您的功能编写测试来开始执行 TDD

下面的清单显示了一个测试,我们可以用来检查贷款金额是否太 大:

@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() {
// given:
LoanApplication application = new LoanApplication(new Client("1234567890"),
99999);
// when:
LoanApplicationResult loanApplication = service.loanApplication(application);
// then:
assertThat(loanApplication.getLoanApplicationStatus())
.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
}

假设您已经编写了新功能的测试。如果申请贷款大 收到金额后,系统应拒绝该贷款申请并进行一些描述。

4.2.2. 编写缺少的实现

在某个时间点,您需要向欺诈检测服务发送请求。假设 您需要发送包含客户端 ID 和金额的请求 客户想借。您希望使用该方法将其发送到 URL。 为此,可以使用类似于以下内容的代码:​​/fraudcheck​​​​PUT​

ResponseEntity response = restTemplate.exchange(
"http://localhost:" + port + fraudCheck(), HttpMethod.PUT,
new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

为简单起见,欺诈检测服务的端口设置为 ,并且 应用程序运行。​​8080​​​​8090​

如果此时开始测试,它将中断,因为当前没有服务在端口上运行。​​8080​

4.2.3. 在本地克隆欺诈检测服务存储库

您可以从使用服务器端合约开始。为此,您必须首先 通过运行以下命令克隆它:

$ git clone https://your-git-server.com/server-side.git local-http-server-repo

4.2.4. 在欺诈检测服务的存储库中本地定义合约

作为消费者,您需要定义您想要实现的目标。您需要制定 您的期望。为此,请编写以下协定:

将合同放在文件夹中。文件夹 很重要,因为生成者的测试基类名称引用该文件夹。​​src/test/resources/contracts/fraud​​​​fraud​

以下示例显示了我们在 Groovy 和 YAML 中的合约:

/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package contracts

org.springframework.cloud.contract.spec.Contract.make {
request { // (1)
method 'PUT' // (2)
url '/fraudcheck' // (3)
body([ // (4)
"client.id": $(regex('[0-9]{10}')),
loanAmount : 99999
])
headers { // (5)
contentType('application/json')
}
}
response { // (6)
status OK() // (7)
body([ // (8)
fraudCheckStatus : "FRAUD",
"rejection.reason": "Amount too high"
])
headers { // (9)
contentType('application/json')
}
}
}

/*
From the Consumer perspective, when shooting a request in the integration test:

(1) - If the consumer sends a request
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the response will be sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` equal to `application/json`

From the Producer perspective, in the autogenerated producer-side test:

(1) - A request will be sent to the producer
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the test will assert if the response has been sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` matching `application/json.*`
*/

YML合同非常简单。但是,当您查看合同时 用静态类型的Groovy DSL编写,你可能想知道零件是什么。通过使用这种表示法,春云 合约允许您定义 JSON 块、URL 或其他动态结构的各个部分。在这种情况下 标识符或时间戳,则无需对值进行硬编码。你想允许一些 不同的值范围。要启用值范围,您可以设置正则表达式 与消费者端的这些值相匹配。您可以通过以下任一方式提供身体 地图表示法或带插值的字符串。我们强烈建议使用地图符号。​​value(client(…), server(…))​

要设置协定,您必须了解地图表示法。请参阅有关 JSON 的 Groovy 文档。

前面显示的合同是双方之间的协议:

  • 如果发送的 HTTP 请求包含以下所有:
  • 端点上的方法PUT/fraudcheck
  • 具有与正则表达式匹配且等于client.id[0-9]{10}loanAmount99999
  • 值为Content-Typeapplication/vnd.fraud.v1+json
  • 然后向消费者发送一个 HTTP 响应
  • 有状态200
  • 包含一个 JSON 正文,其字段包含值 of and 值为fraudCheckStatusFRAUDrejectionReasonAmount too high
  • 具有值为Content-Typeapplication/vnd.fraud.v1+json

准备好在集成测试中实际检查 API 后,您需要 在本地安装存根。

4.2.5. 添加春云合约验证器插件

我们可以添加Maven或Gradle插件。在此示例中,我们展示了如何添加 Maven。 首先,我们添加 BOM,如以下示例所示:​​Spring Cloud Contract​




org.springframework.cloud
spring-cloud-dependencies
${spring-cloud-release.version}
pom
import

接下来,添加 Maven 插件,如以下示例所示:​​Spring Cloud Contract Verifier​


org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true

com.example.fraud





org.springframework.cloud
spring-cloud-contract-pact
${spring-cloud-contract.version}


自从添加了插件以来,您将获得功能,其中, 从提供的合同:​​Spring Cloud Contract Verifier​

  • 生成并运行测试
  • 生产和安装存根

您不想生成测试,因为作为消费者,您只想使用 存根。您需要跳过测试生成和调用。为此,请运行以下命令:

$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests

运行这些命令后,您应该会在日志中看到类似于以下内容的内容:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

以下行非常重要:

[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

它确认的存根已安装在本地 存储 库。​​http-server​

4.2.6. 运行集成测试

为了从春季云合约存根运行器自动功能中获利 存根下载,您必须在使用者端项目中执行以下操作():​​Loan Application service​

  1. 添加物料清单,如下所示:Spring Cloud Contract


<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud-release-train.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
  1. 将依赖项添加到,如下所示:Spring Cloud Contract Stub Runner
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency>
  1. 注释您的测试类。在注释中,为存根运行程序提供 and,以下载您的存根 合作。@AutoConfigureStubRunnergroup-idartifact-id
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {
"com.example:http-server-dsl:0.0.1:stubs"}, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {
  1. (可选)因为您正在离线与协作者一起玩,所以您 还可以提供离线工作开关()。StubRunnerProperties.StubsMode.LOCAL

现在,当您运行测试时,您会在日志中看到类似于以下输出的内容:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

此输出意味着存根运行程序已找到您的存根并为您的应用程序启动了服务器 具有组 ID 和项目 ID 与版本一起 存根和端口上的分类器。​​com.example​​​​http-server​​​​0.0.1-SNAPSHOT​​​​stubs​​​​8080​

​​4.2.7. 提交拉取请求​​

到目前为止,您所做的是一个迭代过程。你可以玩 合同,在本地安装它,并在消费者端工作,直到合同工作 你希望。

对结果满意且测试通过后,可以将拉取请求发布到 服务器端。目前,消费者方面的工作已经完成。

​​4.3. 生产者端(欺诈检测服务器)​​

作为欺诈检测服务器(贷款发放服务的服务器)的开发人员,您 可能需要:

  • 接管拉取请求
  • 编写缺少的实现
  • 部署应用程序

以下 UML 图显示了欺诈检测流程:

Spring Cloud 介绍_应用程序_08

4.3.1. 接管拉取请求

提醒一下,下面的清单显示了初始实现:

@RequestMapping(value = "/fraudcheck", method = PUT)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}

然后,您可以运行以下命令:

$ git checkout -b contract-change-pr master
$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr

必须添加自动生成的测试所需的依赖项,如下所示:


org.springframework.cloud
spring-cloud-starter-contract-verifier
test

在 Maven 插件的配置中,必须传递属性,如下所示:​​packageWithBaseClasses​

<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
<configuration>
<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
<!-- <convertToYaml>true</convertToYaml>-->
</configuration>
<!-- if additional dependencies are needed e.g. for Pact -->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-pact</artifactId>
<version>${spring-cloud-contract.version}</version>
</dependency>
</dependencies>
</plugin>

此示例通过设置属性使用“基于约定”的命名。这样做意味着最后两个包结合起来 创建基测试类的名称。在我们的案例中,合同是根据下达的。由于您没有从 文件夹,只选择一个,应该是。添加后缀和 利用。这为您提供了测试类名。​​packageWithBaseClasses​​​​src/test/resources/contracts/fraud​​​​contracts​​​​fraud​​​​Base​​​​fraud​​​​FraudBase​

所有生成的测试都扩展了该类。在那边,你可以设置你的 Spring 上下文 或任何必要的东西。在这种情况下,您应该使用​​放心 MVC​​​来 启动服务器端。以下清单显示了类:​​FraudDetectionController​​​​FraudBase​

/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.fraud;

import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.jupiter.api.BeforeEach;

public class FraudBase {

@BeforeEach
public void setup() {
RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
new FraudStatsController(stubbedStatsProvider()));
}

private StatsProvider stubbedStatsProvider() {
return fraudType -> {
switch (fraudType) {
case DRUNKS:
return 100;
case ALL:
return 200;
}
return 0;
};
}

public void assertThatRejectionReasonIsNull(Object rejectionReason) {
assert rejectionReason == null;
}

}

现在,如果你运行,你会得到类似于以下输出的东西:​​./mvnw clean install​

Results :

Tests in error:
ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...

发生此错误的原因是,您有一个从中生成测试的新协定,并且 失败,因为您尚未实现该功能。自动生成的测试看起来 像下面的测试方法:

@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");

// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}

如果你使用了 Groovy DSL,你可以看到块中存在的所有合约部分都被注入到测试中。 如果使用 YAML,则同样适用于 的各部分。​​producer()​​​​value(consumer(…), producer(…))​​​​matchers​​​​response​

请注意,在生产者方面,您也在执行TDD。表达期望 以测试的形式。此测试使用 URL 向我们自己的应用程序发送请求, 标头和协定中定义的正文。它还期望精确定义的值 在响应中。换句话说,你有,和的部分。是时候将 the转变为。​​red​​​​red​​​​green​​​​refactor​​​​red​​​​green​

4.3.2. 编写缺少的实现

因为你知道预期的输入和预期的输出,所以你可以写下缺失的 实现如下:

@RequestMapping(value = "/fraudcheck", method = PUT)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
if (amountGreaterThanThreshold(fraudCheck)) {
return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
}
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}

再次运行时,测试通过。自春云 合约验证器插件将测试添加到,您可以 实际上,从 IDE 运行这些测试。​​./mvnw clean install​​​​generated-test-sources​

4.3.3. 部署应用程序

完成工作后,可以部署更改。为此,您必须首先合并 通过运行以下命令进行分支:

$ git checkout master
$ git merge --no-ff contract-change-pr
$ git push origin master

您的 CI 可能会运行一个命令,例如,该命令将发布 应用程序和存根项目。​​./mvnw clean deploy​

4.4. 消费者方(贷款发放),最后一步

作为贷款发放服务的开发人员(欺诈检测服务器的使用者),您需要:

  • 将我们的功能分支合并到master
  • 切换到在线工作模式

以下 UML 图显示了进程的最终状态:

Spring Cloud 介绍_应用程序_09

4.4.1. 将分支合并到主节点

以下命令显示了使用 Git 将分支合并到 master 中的一种方法:

$ git checkout master
$ git merge --no-ff contract-change-pr

4.4.2. 在线工作

现在,您可以禁用春云合约存根运行程序的离线工作,并指示 包含存根的存储库所在的位置。此时,服务器的存根 从Nexus/Artifactory自动下载。您可以将值设置为 to。以下代码显示了 通过更改属性来实现相同的操作:​​stubsMode​​​​REMOTE​

stubrunner:
ids: 'com.example:http-server-dsl:+:stubs:8080'
repositoryRoot: https://repo.spring.io/libs-snapshot

就是这样。您已完成本教程。

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
Spring Cloud Consul 2022-12-07 02:19:36