spring-cloud-circuitbreaker.md 27.3 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4
# Spring Cloud断路器

**2.1.1**

茶陵後's avatar
茶陵後 已提交
5
## 1.使用文档
茶陵後's avatar
茶陵後 已提交
6 7 8

Spring Cloud Circuitbreaker 项目包含 Resilience4J 和 Spring Retry 的实现。在 Spring cloud circuitbreaker 中实现的 API 是在 Spring cloud commons 中实现的。这些 API 的使用文档位于[Spring Cloud Commons documentation](https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-circuit-breaker)中。

茶陵後's avatar
茶陵後 已提交
9
### 1.1.配置弹性 4J 断路器
茶陵後's avatar
茶陵後 已提交
10

茶陵後's avatar
茶陵後 已提交
11
#### 1.1.1.初学者
茶陵後's avatar
茶陵後 已提交
12 13 14 15 16 17 18

弹性 4J 实现有两个启动器,一个用于反应性应用程序,另一个用于非反应性应用程序。

* `org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j`-无反应应用

* `org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j`-反应性应用

茶陵後's avatar
茶陵後 已提交
19
#### 1.1.2.自动配置
茶陵後's avatar
茶陵後 已提交
20 21 22

通过将`spring.cloud.circuitbreaker.resilience4j.enabled`设置为`false`,可以禁用 Resilience4j 自动配置。

茶陵後's avatar
茶陵後 已提交
23
#### 1.1.3.默认配置
茶陵後's avatar
茶陵後 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

要为你的所有断路器提供默认配置,请创建一个`Customize` Bean,它传递一个`Resilience4JCircuitBreakerFactory``ReactiveResilience4JCircuitBreakerFactory``configureDefault`方法可用于提供默认配置。

```
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
    return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
            .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build())
            .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
            .build());
}
```

##### [](#reactive-example)[反应式示例](#reactive-example)

```
@Bean
public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
    return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
            .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
            .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build()).build());
}
```

茶陵後's avatar
茶陵後 已提交
48
#### 1.1.4.特定断路器配置
茶陵後's avatar
茶陵後 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

与提供默认配置类似,你可以创建一个`Customize` Bean 这是传递一个`Resilience4JCircuitBreakerFactory``ReactiveResilience4JCircuitBreakerFactory`

```
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
    return factory -> factory.configure(builder -> builder.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
            .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build()), "slow");
}
```

除了配置被创建的断路器之外,你还可以在断路器被创建之后但在断路器被返回给调用者之前自定义断路器。要做到这一点,你可以使用`addCircuitBreakerCustomizer`方法。这对于将事件处理程序添加到 Resilience4J 断路器非常有用。

```
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
    return factory -> factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker.getEventPublisher()
    .onError(normalFluxErrorConsumer).onSuccess(normalFluxSuccessConsumer), "normalflux");
}
```

##### [](#reactive-example-2)[反应式示例](#reactive-example-2)

```
@Bean
public Customizer<ReactiveResilience4JCircuitBreakerFactory> slowCustomizer() {
    return factory -> {
        factory.configure(builder -> builder
        .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build())
        .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()), "slow", "slowflux");
        factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker.getEventPublisher()
            .onError(normalFluxErrorConsumer).onSuccess(normalFluxSuccessConsumer), "normalflux");
     };
}
```

茶陵後's avatar
茶陵後 已提交
85
#### 1.1.5.断路器特性配置
茶陵後's avatar
茶陵後 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

你可以在应用程序的配置属性文件中配置`CircuitBreaker``TimeLimiter`实例。属性配置比 Java`Customizer`配置具有更高的优先级。

```
resilience4j.circuitbreaker:
 instances:
     backendA:
         registerHealthIndicator: true
         slidingWindowSize: 100
     backendB:
         registerHealthIndicator: true
         slidingWindowSize: 10
         permittedNumberOfCallsInHalfOpenState: 3
         slidingWindowType: TIME_BASED
         recordFailurePredicate: io.github.robwin.exception.RecordFailurePredicate

resilience4j.timelimiter:
 instances:
     backendA:
         timeoutDuration: 2s
         cancelRunningFuture: true
     backendB:
         timeoutDuration: 1s
         cancelRunningFuture: false
```

有关 Resilience4j 属性配置的更多信息,请参见[Resilience4J Spring Boot 2 Configuration](https://resilience4j.readme.io/docs/getting-started-3#configuration)

茶陵後's avatar
茶陵後 已提交
114
#### 1.1.6.舱壁模式支撑
茶陵後's avatar
茶陵後 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

如果`resilience4j-bulkhead`在 Classpath 上, Spring Cloud Circuitbreaker 将用 Resilience4J 隔板包装所有方法。你可以通过将`spring.cloud.circuitbreaker.bulkhead.resilience4j.enabled`设置为`false`来禁用 Resilience4J 舱壁。

Spring Cloud Circuitbreaker Resilience4J 提供了两种舱壁模式的实现方式:

* 使用信号量的`SemaphoreBulkhead`

* 使用有界队列和固定线程池的`FixedThreadPoolBulkhead`

默认情况下, Spring Cloud Circuitbreaker Resilience4j 使用`FixedThreadPoolBulkhead`。有关舱壁模式实现的更多信息,请参见[弹性 4J 舱壁](https://resilience4j.readme.io/docs/bulkhead)

`Customizer<Resilience4jBulkheadProvider>`可用于提供默认的`Bulkhead``ThreadPoolBulkhead`配置。

```
@Bean
public Customizer<Resilience4jBulkheadProvider> defaultBulkheadCustomizer() {
    return provider -> provider.configureDefault(id -> new Resilience4jBulkheadConfigurationBuilder()
        .bulkheadConfig(BulkheadConfig.custom().maxConcurrentCalls(4).build())
        .threadPoolBulkheadConfig(ThreadPoolBulkheadConfig.custom().coreThreadPoolSize(1).maxThreadPoolSize(1).build())
        .build()
);
}
```

茶陵後's avatar
茶陵後 已提交
139
#### 1.1.7.特定舱壁结构
茶陵後's avatar
茶陵後 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

与证明默认的“bulkhead”或“threadpoolbulkhead”配置类似,你可以创建`Customize` Bean 这传递了一个`Resilience4jBulkheadProvider`

```
@Bean
public Customizer<Resilience4jBulkheadProvider> slowBulkheadProviderCustomizer() {
    return provider -> provider.configure(builder -> builder
        .bulkheadConfig(BulkheadConfig.custom().maxConcurrentCalls(1).build())
        .threadPoolBulkheadConfig(ThreadPoolBulkheadConfig.ofDefaults()), "slowBulkhead");
}
```

除了配置所创建的舱壁之外,你还可以在舱壁和线程池的舱壁被创建之后但在它们被返回给调用方之前自定义它们。要做到这一点,你可以使用`addBulkheadCustomizer``addThreadPoolBulkheadCustomizer`方法。

##### [](#bulkhead-example)[舱壁示例](#bulkhead-example)

```
@Bean
public Customizer<Resilience4jBulkheadProvider> customizer() {
    return provider -> provider.addBulkheadCustomizer(bulkhead -> bulkhead.getEventPublisher()
        .onCallRejected(slowRejectedConsumer)
        .onCallFinished(slowFinishedConsumer), "slowBulkhead");
}
```

##### [](#thread-pool-bulkhead-example)[线程池隔板示例](#thread-pool-bulkhead-example)

```
@Bean
public Customizer<Resilience4jBulkheadProvider> slowThreadPoolBulkheadCustomizer() {
    return provider -> provider.addThreadPoolBulkheadCustomizer(threadPoolBulkhead -> threadPoolBulkhead.getEventPublisher()
        .onCallRejected(slowThreadPoolRejectedConsumer)
        .onCallFinished(slowThreadPoolFinishedConsumer), "slowThreadPoolBulkhead");
}
```

茶陵後's avatar
茶陵後 已提交
176
#### 1.1.8.舱壁属性配置
茶陵後's avatar
茶陵後 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

你可以在应用程序的配置属性文件中配置 ThreadPoolBulkhead 和 SemaphoreBulkhead 实例。属性配置比 Java`Customizer`配置具有更高的优先级。

```
resilience4j.thread-pool-bulkhead:
    instances:
        backendA:
            maxThreadPoolSize: 1
            coreThreadPoolSize: 1
resilience4j.bulkhead:
    instances:
        backendB:
            maxConcurrentCalls: 10
```

有关 Resilience4j 属性配置的更多信息,请参见[Resilience4J Spring Boot 2 Configuration](https://resilience4j.readme.io/docs/getting-started-3#configuration)

茶陵後's avatar
茶陵後 已提交
194
#### 1.1.9.收集指标
茶陵後's avatar
茶陵後 已提交
195 196 197 198 199 200

Spring Cloud断路器弹性 4j 包括自动配置以设置度量收集,只要正确的依赖关系是在 Classpath 上。要启用度量集合,必须包括`org.springframework.boot:spring-boot-starter-actuator``io.github.resilience4j:resilience4j-micrometer`。有关存在这些依赖关系时产生的度量的更多信息,请参见[复原力 4J 文档](https://resilience4j.readme.io/docs/micrometer)

|   |你不必直接包含`micrometer-core`,因为它是由`spring-boot-starter-actuator`引入的|
|---|----------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
201
### 1.2. Configuring Spring Retry Circuit Breakers
茶陵後's avatar
茶陵後 已提交
202 203 204

Spring Retry 为 Spring 应用程序提供声明性重试支持。该项目的一个子集包括实现断路器功能的能力。 Spring Retry 通过它的[`CircuitBreakerRetryPolicy`](https://github.com/ Spring-projects/ Spring-retry/blob/master/SRC/main/java/org/springframework/retry/policy/circuitbreakerretrygt.java)和<<r="134"/>的组合提供了一个断路器实现。所有使用 Spring 重试创建的断路器都将使用`CircuitBreakerRetryPolicy`和[`DefaultRetryState`](https://github.com/ Spring-projects/ Spring-retry/blob/master/SRC/main/java/org/springframework/retry/support/defaultrystate.java)创建。这两个类都可以使用`SpringRetryConfigBuilder`进行配置。

茶陵後's avatar
茶陵後 已提交
205
#### 1.2.1.默认配置
茶陵後's avatar
茶陵後 已提交
206 207 208 209 210 211 212 213 214 215 216

要为你的所有断路器提供默认配置,请创建一个`Customize` Bean,传递一个`SpringRetryCircuitBreakerFactory``configureDefault`方法可用于提供默认配置。

```
@Bean
public Customizer<SpringRetryCircuitBreakerFactory> defaultCustomizer() {
    return factory -> factory.configureDefault(id -> new SpringRetryConfigBuilder(id)
        .retryPolicy(new TimeoutRetryPolicy()).build());
}
```

茶陵後's avatar
茶陵後 已提交
217
#### 1.2.2.特定断路器配置
茶陵後's avatar
茶陵後 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

与提供默认配置类似,你可以创建`Customize` Bean 这是传递的`SpringRetryCircuitBreakerFactory`

```
@Bean
public Customizer<SpringRetryCircuitBreakerFactory> slowCustomizer() {
    return factory -> factory.configure(builder -> builder.retryPolicy(new SimpleRetryPolicy(1)).build(), "slow");
}
```

除了配置被创建的断路器之外,你还可以在断路器被创建之后但在断路器被返回给调用者之前自定义断路器。要做到这一点,你可以使用`addRetryTemplateCustomizers`方法。这对于将事件处理程序添加到`RetryTemplate`非常有用。

```
@Bean
public Customizer<SpringRetryCircuitBreakerFactory> slowCustomizer() {
    return factory -> factory.addRetryTemplateCustomizers(retryTemplate -> retryTemplate.registerListener(new RetryListener() {

        @Override
        public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
            return false;
        }

        @Override
        public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {

        }

        @Override
        public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {

        }
    }));
}
```

茶陵後's avatar
茶陵後 已提交
253
## 2.建筑物
茶陵後's avatar
茶陵後 已提交
254

茶陵後's avatar
茶陵後 已提交
255
### 2.1.基本编译和测试
茶陵後's avatar
茶陵後 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

要构建源代码,你需要安装 JDK17。

Spring Cloud 在大多数与构建相关的活动中使用 Maven,你应该能够通过克隆感兴趣的项目并键入来很快地开始工作。

```
$ ./mvnw install
```

|   |你也可以自己安装 Maven(\>=3.3.3),并在下面的示例中运行`mvn`命令<br/>来代替`./mvnw`。如果你这样做,那么如果你的本地 Maven 设置不<br/>包含 Spring 预发布工件的存储库声明,那么你可能还需要添加`-P spring`。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |请注意,你可能需要通过使用<br/>设置`-Xmx512m -XX:MaxPermSize=128m`这样的值的`MAVEN_OPTS`环境变量来增加 Maven 可用的<br/>内存量。我们试图在<br/>`.mvn`配置中覆盖此内容,因此,如果你发现必须这样做才能使<br/>构建成功,请举出一张票来将设置添加到<br/>源代码控制中。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

需要中间件(即 Redis)进行测试的项目通常需要安装并运行[Docker]([WWW.docker.com/get-started](https://www.docker.com/get-started))的本地实例。

茶陵後's avatar
茶陵後 已提交
273
### 2.2.文件
茶陵後's avatar
茶陵後 已提交
274 275 276

Spring-cloud-build 模块具有一个“DOCS”配置文件,如果你将其打开,它将尝试从`src/main/asciidoc`构建 ASCIIDoc 源。作为该过程的一部分,它将寻找`README.adoc`,并通过加载所有的包含来处理它,但不是解析或呈现它,只是将其复制到`${main.basedir}`(默认为`$/tmp/releaser-1645116950347-0/spring-cloud-circuitbreaker/docs`,即项目的根)。如果 README 中有任何更改,那么在构建 Maven 之后,它将在正确的位置显示为经过修改的文件。只要承诺并推动改变就行了。

茶陵後's avatar
茶陵後 已提交
277
### 2.3.使用代码
茶陵後's avatar
茶陵後 已提交
278 279 280

如果你没有 IDE 偏好,我们建议你在使用代码时使用[Spring Tools Suite](https://www.springsource.com/developer/sts)[Eclipse](https://eclipse.org)。我们使用[m2eclipse](https://eclipse.org/m2e/)Eclipse 插件来提供 Maven 支持。其他 IDE 和工具也应该在没有问题的情况下工作,只要它们使用 Maven 3.3.3 或更好。

茶陵後's avatar
茶陵後 已提交
281
#### 2.3.1. Activate the Spring Maven profile
茶陵後's avatar
茶陵後 已提交
282 283 284

Spring Cloud项目需要激活“ Spring” Maven 配置文件,以解析 Spring 里程碑和快照存储库。使用你首选的 IDE 将此配置文件设置为活动的,否则你可能会遇到构建错误。

茶陵後's avatar
茶陵後 已提交
285
#### 2.3.2.用 M2Eclipse 导入到 Eclipse 中
茶陵後's avatar
茶陵後 已提交
286 287 288 289 290 291

在使用 Eclipse 时,我们推荐[m2eclipse](https://eclipse.org/m2e/)Eclipse 插件。如果你还没有安装 M2Eclipse,它可以从“Eclipse 市场”获得。

|   |较早版本的 M2E 不支持 Maven 3.3,因此,一旦<br/>项目导入到 Eclipse 中,你还需要告诉<br/>M2Eclipse 为项目使用正确的配置文件。如果你<br/>在项目中看到许多与 POM 相关的错误,请检查<br/>是否有最新的安装。如果你不能升级 M2E,<br/>将“ Spring”配置文件添加到你的`settings.xml`。或者,你可以<br/>将存储库设置从父<br/> POM 的“ Spring”配置文件复制到你的`settings.xml`中。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
292
#### 2.3.3.在没有 M2Eclipse 的情况下导入 Eclipse
茶陵後's avatar
茶陵後 已提交
293 294 295 296 297 298 299 300 301

如果不喜欢使用 M2Eclipse,可以使用以下命令生成 Eclipse 项目元数据:

```
$ ./mvnw eclipse:eclipse
```

可以通过从`file`菜单中选择`import existing projects`来导入生成的 Eclipse 项目。

茶陵後's avatar
茶陵後 已提交
302
## 3.贡献
茶陵後's avatar
茶陵後 已提交
303 304 305

Spring Cloud 是在非限制性的 Apache2.0 许可下发布的,并遵循非常标准的 GitHub 开发流程,使用 GitHub Tracker 处理问题并将拉请求合并到 Master 中。如果你想贡献一些微不足道的东西,请不要犹豫,但要遵循下面的指导方针。

茶陵後's avatar
茶陵後 已提交
306
### 3.1.签署贡献者许可协议
茶陵後's avatar
茶陵後 已提交
307 308 309

在我们接受一个重要的补丁或拉请求之前,我们需要你签署[贡献者许可协议](https://cla.pivotal.io/sign/spring)。签署贡献者协议并不会授予任何人对主库的提交权限,但这确实意味着我们可以接受你的贡献,并且如果我们接受了,你将获得作者信用。活跃的贡献者可能会被要求加入核心团队,并被赋予合并拉请求的能力。

茶陵後's avatar
茶陵後 已提交
310
### 3.2.行为守则
茶陵後's avatar
茶陵後 已提交
311 312 313

该项目遵守贡献者契约[行为守则](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc)。通过参与,你将被期望坚持这一准则。请向[[电子邮件保护]]报告不可接受的行为(/cdn-cgi/l/email-protection#4c3f3c3e25222b612f23282961232a612f232228392f380c3c253a23382d20622523)。

茶陵後's avatar
茶陵後 已提交
314
### 3.3.守则惯例和内部管理
茶陵後's avatar
茶陵後 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

这些都不是拉请求所必需的,但它们都会有所帮助。它们也可以在原始的拉请求之后但在合并之前添加。

* 使用 Spring 框架代码格式约定。如果使用 Eclipse,则可以使用`eclipse-code-formatter.xml`文件从[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml)项目导入格式化设置。如果使用 IntelliJ,可以使用[Eclipse 代码格式化插件](https://plugins.jetbrains.com/plugin/6546)导入相同的文件。

* 确保所有新的`.java`文件都有一个简单的 Javadoc 类注释,其中至少有一个`@author`标记来标识你,并且最好至少有一个段落来说明类的用途。

* 将 ASF 许可标头注释添加到所有新的`.java`文件(从项目中的现有文件复制)

* 将自己作为`@author`添加到要进行实质性修改的.java 文件中(不仅仅是外观上的更改)。

* 添加一些 Javadocs,如果你更改了名称空间,还可以添加一些 XSDDOC 元素。

* 几个单元测试也会有很大帮助——必须有人去做。

* 如果没有其他人正在使用你的分支,请将它重新设置为当前的主分支(或主项目中的其他目标分支)。

* 在写提交消息时,请遵循[这些约定](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),如果你正在修复现有的问题,请在提交消息的末尾添加`Fixes gh-XXXX`(其中 xxxx 是问题编号)。

茶陵後's avatar
茶陵後 已提交
334
### 3.4.checkstyle
茶陵後's avatar
茶陵後 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

Spring Cloud构建附带一组 CheckStyle 规则。你可以在`spring-cloud-build-tools`模块中找到它们。该模块下最值得注意的文件是:

Spring-云构建工具/

```
└── src
    ├── checkstyle
    │   └── checkstyle-suppressions.xml (3)
    └── main
        └── resources
            ├── checkstyle-header.txt (2)
            └── checkstyle.xml (1)
```

|**1**|默认的 checkstyle 规则|
|-----|-------------------------|
|**2**|文件头设置|
|**3**|默认抑制规则|

茶陵後's avatar
茶陵後 已提交
355
#### 3.4.1.checkstyle 配置
茶陵後's avatar
茶陵後 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

checkstyle 规则是**默认禁用**。要将 checkstyle 添加到项目中,只需定义以下属性和插件。

POM.xml

```
<properties>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> (1)
        <maven-checkstyle-plugin.failsOnViolation>true
        </maven-checkstyle-plugin.failsOnViolation> (2)
        <maven-checkstyle-plugin.includeTestSourceDirectory>true
        </maven-checkstyle-plugin.includeTestSourceDirectory> (3)
</properties>

<build>
        <plugins>
            <plugin> (4)
                <groupId>io.spring.javaformat</groupId>
                <artifactId>spring-javaformat-maven-plugin</artifactId>
            </plugin>
            <plugin> (5)
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>

    <reporting>
        <plugins>
            <plugin> (5)
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>
    </reporting>
</build>
```

|**1**|构建 checkstyle 错误失败|
|-----|--------------------------------------------------------------------------------------------------------------|
|**2**|构建 checkstyle 冲突失败|
|**3**|CheckStyle 还分析了测试源|
|**4**|添加 Spring Java 格式插件,该插件将重新格式化你的代码,以传递大多数 CheckStyle 格式设置规则|
|**5**|将 CheckStyle 插件添加到构建和报告阶段|

如果你需要抑制一些规则(例如行长需要更长),那么在`${project.root}/src/checkstyle/checkstyle-suppressions.xml`下定义一个文件就足够了。示例:

projectRoot/SRC/checkstyle/checkstyle-suppresions.xml

```
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
        "-//Puppy Crawl//DTD Suppressions 1.1//EN"
        "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
    <suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
    <suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
</suppressions>
```

建议将`${spring-cloud-build.rootFolder}/.editorconfig``${spring-cloud-build.rootFolder}/.springformat`复制到你的项目中。这样,将应用一些默认的格式设置规则。你可以通过运行以下脚本来实现此目的:

```
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
$ touch .springformat
```

茶陵後's avatar
茶陵後 已提交
422
### 3.5.IDE 设置
茶陵後's avatar
茶陵後 已提交
423

茶陵後's avatar
茶陵後 已提交
424
#### 3.5.1.Intellij 思想
茶陵後's avatar
茶陵後 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

为了设置 IntelliJ,你应该导入我们的编码约定、检查配置文件并设置 CheckStyle 插件。以下文件可以在[Spring Cloud Build](https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools)项目中找到。

Spring-云构建工具/

```
└── src
    ├── checkstyle
    │   └── checkstyle-suppressions.xml (3)
    └── main
        └── resources
            ├── checkstyle-header.txt (2)
            ├── checkstyle.xml (1)
            └── intellij
                ├── Intellij_Project_Defaults.xml (4)
                └── Intellij_Spring_Boot_Java_Conventions.xml (5)
```

|**1**|默认的 checkstyle 规则|
|-----|--------------------------------------------------------------------------|
|**2**|文件头设置|
|**3**|默认抑制规则|
|**4**|适用大多数 CheckStyle 规则的 IntelliJ 的项目默认值|
|**5**|适用大多数 CheckStyle 规则的 IntelliJ 的项目风格约定|

![Code style](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-code-style.png)

图 1。代码样式

转到`File``Settings``Editor``Code style`。点击`Scheme`区域旁边的图标。在这里,单击`Import Scheme`值并选择`Intellij IDEA code style XML`选项。导入`spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml`文件。

![Code style](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-inspections.png)

图 2。检查剖面

转到`File``Settings``Editor``Inspections`。点击`Profile`区域旁边的图标。在那里,单击`Import Profile`并导入`spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml`文件。

checkstyle

要让 IntelliJ 使用 CheckStyle,你必须安装`Checkstyle`插件。建议还安装`Assertions2Assertj`来自动转换 JUnit 断言

![Checkstyle](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/images/intellij-checkstyle.png)

转到`File``Settings``Other settings``Checkstyle`。点击`Configuration file`区域中的`+`图标。在这里,你必须定义应该从哪里选择 CheckStyle 规则。在上面的图片中,我们从克隆的云构建存储库中选择了规则。但是,你可以指向 Spring Cloud Build 的 GitHub 存储库(例如`checkstyle.xml`:`[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml)`)。我们需要提供以下变量:

* `checkstyle.header.file`-请将其指向 Spring Cloud Build 的`spring-cloud-build-tools/src/main/resources/checkstyle-header.txt`文件,可以在你的克隆 repo 中,也可以通过`[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt)`URL。

* `checkstyle.suppressions.file`-默认抑制。请将它指向 Spring Cloud Build 的`spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml`文件,或者在你的克隆 repo 中,或者通过`[raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml)`URL。

* `checkstyle.additional.suppressions.file`-此变量对应于本地项目中的抑制。例如,你正在处理`spring-cloud-contract`。然后指向`project-root/src/checkstyle/checkstyle-suppressions.xml`文件夹。`spring-cloud-contract`的示例是:`/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`

|   |请记住将`Scan Scope`设置为`All sources`,因为我们为生产和测试源应用了 checkstyle 规则。|
|---|------------------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
479
### 3.6.重复查找器
茶陵後's avatar
茶陵後 已提交
480 481 482

Spring Cloud构建带来了`basepom:duplicate-finder-maven-plugin`,这使得能够在 Java Classpath 上标记重复的和冲突的类和资源。

茶陵後's avatar
茶陵後 已提交
483
#### 3.6.1.重复查找器配置
茶陵後's avatar
茶陵後 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

重复查找器是**默认启用**,将在 Maven 构建的`verify`阶段运行,但是只有在将`duplicate-finder-maven-plugin`添加到项目的`build`部分`POM.xml`时,它才会在项目中生效。

pom.xml

```
<build>
    <plugins>
        <plugin>
            <groupId>org.basepom.maven</groupId>
            <artifactId>duplicate-finder-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
```

对于其他属性,我们设置了[插件文档](https://github.com/basepom/duplicate-finder-maven-plugin/wiki)中列出的默认值。

你可以轻松地重写它们,但可以使用`duplicate-finder-maven-plugin`前缀设置所选属性的值。例如,将`duplicate-finder-maven-plugin.skip`设置为`true`,以便在构建中跳过重复检查。

如果需要将`ignoredClassPatterns``ignoredResourcePatterns`添加到设置中,请确保将它们添加到项目的插件配置部分中:

```
<build>
    <plugins>
        <plugin>
            <groupId>org.basepom.maven</groupId>
            <artifactId>duplicate-finder-maven-plugin</artifactId>
            <configuration>
                <ignoredClassPatterns>
                    <ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
                    <ignoredClassPattern>.*module-info</ignoredClassPattern>
                </ignoredClassPatterns>
                <ignoredResourcePatterns>
                    <ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
                </ignoredResourcePatterns>
            </configuration>
        </plugin>
    </plugins>
</build>
茶陵後's avatar
茶陵後 已提交
524
```