此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Integration 6.5.1! |
提供的咨询课程
除了提供应用AOP通知类的通用机制外,Spring Integration还提供了以下开箱即用的通知实现:
-
RequestHandlerRetryAdvice
(在重试建议中描述) -
RequestHandlerCircuitBreakerAdvice
(在断路器建议中描述) -
ExpressionEvaluatingRequestHandlerAdvice
(在表达式建议中描述) -
RateLimiterRequestHandlerAdvice
(在速率限制器建议中描述) -
CacheRequestHandlerAdvice
(在缓存建议中描述) -
ReactiveRequestHandlerAdvice
(在反应性建议中描述) -
ContextHolderRequestHandlerAdvice
(在上下文持有人建议中描述) -
LockRequestHandlerAdvice
(在锁定建议中描述)
重试建议
重试建议 (o.s.i.handler.advice.RequestHandlerRetryAdvice
)利用了 Spring Retry 项目提供的丰富重试机制。
的核心组件spring-retry
是RetryTemplate
,它允许配置复杂的重试方案,包括RetryPolicy
和BackoffPolicy
策略(具有许多实现)以及RecoveryCallback
策略,以确定重试用尽时要采取的作。
- 无状态重试
-
无状态重试是指重试活动完全在通知中处理的情况。 线程暂停(如果配置为这样做)并重试作。
- 有状态重试
-
有状态重试是指重试状态在通知中进行管理,但抛出异常并且调用方重新提交请求的情况。 有状态重试的一个示例是,当我们希望消息发起者(例如 JMS)负责重新提交,而不是在当前线程上执行它时。 有状态重试需要某种机制来检测重试的提交。
有关spring-retry
,请参阅项目的 Javadoc 和 Spring Batch 的参考文档,其中spring-retry
起源。
默认的退后行为是不退后退。 立即尝试重试。 使用导致线程在两次尝试之间暂停的回退策略可能会导致性能问题,包括内存使用过多和线程匮乏。 在高容量环境中,应谨慎使用退避策略。 |
配置重试建议
本节中的示例使用以下内容<service-activator>
总是抛出异常:
public class FailingService {
public void service(String message) {
throw new RuntimeException("error");
}
}
- 简单无状态重试
-
默认值
RetryTemplate
有一个SimpleRetryPolicy
尝试三次。 没有BackOffPolicy
,因此三次尝试是背靠背进行的,两次尝试之间没有延迟。 没有RecoveryCallback
,因此结果是在最后一次失败的重试发生后向调用方抛出异常。 在 Spring Integration 环境中,可以使用error-channel
在入站终结点上。 以下示例使用RetryTemplate
并显示其DEBUG
输出:<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <bean class="o.s.i.handler.advice.RequestHandlerRetryAdvice"/> </int:request-handler-advice-chain> </int:service-activator> DEBUG [task-scheduler-2]preSend on channel 'input', message: [Payload=...] DEBUG [task-scheduler-2]Retry: count=0 DEBUG [task-scheduler-2]Checking for rethrow: count=1 DEBUG [task-scheduler-2]Retry: count=1 DEBUG [task-scheduler-2]Checking for rethrow: count=2 DEBUG [task-scheduler-2]Retry: count=2 DEBUG [task-scheduler-2]Checking for rethrow: count=3 DEBUG [task-scheduler-2]Retry failed last attempt: count=3
- 带恢复的简单无状态重试
-
以下示例将
RecoveryCallback
添加到前面的示例中,并使用ErrorMessageSendingRecoverer
发送ErrorMessage
到频道:<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <bean class="o.s.i.handler.advice.RequestHandlerRetryAdvice"> <property name="recoveryCallback"> <bean class="o.s.i.handler.advice.ErrorMessageSendingRecoverer"> <constructor-arg ref="myErrorChannel" /> </bean> </property> </bean> </int:request-handler-advice-chain> </int:service-activator> DEBUG [task-scheduler-2]preSend on channel 'input', message: [Payload=...] DEBUG [task-scheduler-2]Retry: count=0 DEBUG [task-scheduler-2]Checking for rethrow: count=1 DEBUG [task-scheduler-2]Retry: count=1 DEBUG [task-scheduler-2]Checking for rethrow: count=2 DEBUG [task-scheduler-2]Retry: count=2 DEBUG [task-scheduler-2]Checking for rethrow: count=3 DEBUG [task-scheduler-2]Retry failed last attempt: count=3 DEBUG [task-scheduler-2]Sending ErrorMessage :failedMessage:[Payload=...]
- 使用自定义策略的无状态重试和恢复
-
为了更复杂,我们可以提供定制的建议
RetryTemplate
. 此示例继续使用SimpleRetryPolicy
但将尝试次数增加到四次。 它还添加了一个ExponentialBackoffPolicy
其中第一次重试等待一秒钟,第二次等待五秒,第三次等待 25 秒(总共四次尝试)。 以下列表显示了该示例及其DEBUG
输出:<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <bean class="o.s.i.handler.advice.RequestHandlerRetryAdvice"> <property name="recoveryCallback"> <bean class="o.s.i.handler.advice.ErrorMessageSendingRecoverer"> <constructor-arg ref="myErrorChannel" /> </bean> </property> <property name="retryTemplate" ref="retryTemplate" /> </bean> </int:request-handler-advice-chain> </int:service-activator> <bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate"> <property name="retryPolicy"> <bean class="org.springframework.retry.policy.SimpleRetryPolicy"> <property name="maxAttempts" value="4" /> </bean> </property> <property name="backOffPolicy"> <bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy"> <property name="initialInterval" value="1000" /> <property name="multiplier" value="5.0" /> <property name="maxInterval" value="60000" /> </bean> </property> </bean> 27.058 DEBUG [task-scheduler-1]preSend on channel 'input', message: [Payload=...] 27.071 DEBUG [task-scheduler-1]Retry: count=0 27.080 DEBUG [task-scheduler-1]Sleeping for 1000 28.081 DEBUG [task-scheduler-1]Checking for rethrow: count=1 28.081 DEBUG [task-scheduler-1]Retry: count=1 28.081 DEBUG [task-scheduler-1]Sleeping for 5000 33.082 DEBUG [task-scheduler-1]Checking for rethrow: count=2 33.082 DEBUG [task-scheduler-1]Retry: count=2 33.083 DEBUG [task-scheduler-1]Sleeping for 25000 58.083 DEBUG [task-scheduler-1]Checking for rethrow: count=3 58.083 DEBUG [task-scheduler-1]Retry: count=3 58.084 DEBUG [task-scheduler-1]Checking for rethrow: count=4 58.084 DEBUG [task-scheduler-1]Retry failed last attempt: count=4 58.086 DEBUG [task-scheduler-1]Sending ErrorMessage :failedMessage:[Payload=...]
- 命名空间对无状态重试的支持
-
从 4.0 版开始,由于命名空间对重试建议的支持,可以大大简化上述配置,如以下示例所示:
<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <ref bean="retrier" /> </int:request-handler-advice-chain> </int:service-activator> <int:handler-retry-advice id="retrier" max-attempts="4" recovery-channel="myErrorChannel"> <int:exponential-back-off initial="1000" multiplier="5.0" maximum="60000" /> </int:handler-retry-advice>
在前面的示例中,建议被定义为顶级 Bean,以便它可以在多个
request-handler-advice-chain
实例。 您还可以直接在链中定义通知,如以下示例所示:<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <int:retry-advice id="retrier" max-attempts="4" recovery-channel="myErrorChannel"> <int:exponential-back-off initial="1000" multiplier="5.0" maximum="60000" /> </int:retry-advice> </int:request-handler-advice-chain> </int:service-activator>
一个
<handler-retry-advice>
可以有一个<fixed-back-off>
或<exponential-back-off>
child 元素或没有子元素。 一个<handler-retry-advice>
with no 子元素使用 no back off。 如果没有recovery-channel
,则在重试用尽时引发异常。 命名空间只能用于无状态重试。对于更复杂的环境(自定义策略等),请使用
<bean>
定义。 - 带恢复的简单有状态重试
-
要使重试有状态,我们需要为建议提供
RetryStateGenerator
实现。 此类用于将消息标识为重新提交,以便RetryTemplate
可以确定此消息的重试当前状态。 该框架提供了一个SpelExpressionRetryStateGenerator
,它使用 SpEL 表达式确定消息标识符。 此示例再次使用默认策略(三次尝试,无回退)。 与无状态重试一样,可以自定义这些策略。 以下列表显示了该示例及其DEBUG
输出:<int:service-activator input-channel="input" ref="failer" method="service"> <int:request-handler-advice-chain> <bean class="o.s.i.handler.advice.RequestHandlerRetryAdvice"> <property name="retryStateGenerator"> <bean class="o.s.i.handler.advice.SpelExpressionRetryStateGenerator"> <constructor-arg value="headers['jms_messageId']" /> </bean> </property> <property name="recoveryCallback"> <bean class="o.s.i.handler.advice.ErrorMessageSendingRecoverer"> <constructor-arg ref="myErrorChannel" /> </bean> </property> </bean> </int:request-handler-advice-chain> </int:service-activator> 24.351 DEBUG [Container#0-1]preSend on channel 'input', message: [Payload=...] 24.368 DEBUG [Container#0-1]Retry: count=0 24.387 DEBUG [Container#0-1]Checking for rethrow: count=1 24.387 DEBUG [Container#0-1]Rethrow in retry for policy: count=1 24.387 WARN [Container#0-1]failure occurred in gateway sendAndReceive org.springframework.integration.MessagingException: Failed to invoke handler ... Caused by: java.lang.RuntimeException: foo ... 24.391 DEBUG [Container#0-1]Initiating transaction rollback on application exception ... 25.412 DEBUG [Container#0-1]preSend on channel 'input', message: [Payload=...] 25.412 DEBUG [Container#0-1]Retry: count=1 25.413 DEBUG [Container#0-1]Checking for rethrow: count=2 25.413 DEBUG [Container#0-1]Rethrow in retry for policy: count=2 25.413 WARN [Container#0-1]failure occurred in gateway sendAndReceive org.springframework.integration.MessagingException: Failed to invoke handler ... Caused by: java.lang.RuntimeException: foo ... 25.414 DEBUG [Container#0-1]Initiating transaction rollback on application exception ... 26.418 DEBUG [Container#0-1]preSend on channel 'input', message: [Payload=...] 26.418 DEBUG [Container#0-1]Retry: count=2 26.419 DEBUG [Container#0-1]Checking for rethrow: count=3 26.419 DEBUG [Container#0-1]Rethrow in retry for policy: count=3 26.419 WARN [Container#0-1]failure occurred in gateway sendAndReceive org.springframework.integration.MessagingException: Failed to invoke handler ... Caused by: java.lang.RuntimeException: foo ... 26.420 DEBUG [Container#0-1]Initiating transaction rollback on application exception ... 27.425 DEBUG [Container#0-1]preSend on channel 'input', message: [Payload=...] 27.426 DEBUG [Container#0-1]Retry failed last attempt: count=3 27.426 DEBUG [Container#0-1]Sending ErrorMessage :failedMessage:[Payload=...]
如果将前面的示例与无状态示例进行比较,则可以看到,使用有状态重试时,每次失败时都会向调用方引发异常。
- 重试的异常分类
-
春季重试具有很大的灵活性,可以确定哪些异常可以调用重试。 默认配置会重试所有异常,异常分类器会查看顶级异常。 如果将其配置为仅在
MyException
并且您的应用程序会抛出一个SomeOtherException
其中原因是MyException
,则不会发生重试。从 Spring Retry 1.0.3 开始,
BinaryExceptionClassifier
有一个名为traverseCauses
(默认值为false
). 什么时候true
,它遍历异常原因,直到找到匹配项或遍历原因用完。要使用此分类器进行重试,请使用
SimpleRetryPolicy
使用采用最大尝试次数的构造函数创建,则Map
之Exception
对象,以及traverseCauses
布尔。 然后,您可以将此策略注入RetryTemplate
.
traverseCauses 在这种情况下是必需的,因为用户异常可能包装在MessagingException . |
断路器建议
断路器模式的总体思想是,如果服务当前不可用,请不要浪费时间(和资源)尝试使用它。
这o.s.i.handler.advice.RequestHandlerCircuitBreakerAdvice
实现此模式。
当断路器处于关闭状态时,终结点会尝试调用服务。
如果一定次数的连续尝试失败,断路器将进入打开状态。
当它处于打开状态时,新请求会“快速失败”,并且在一段时间到期之前不会尝试调用服务。
当该时间到期时,断路器将设置为半开状态。 当处于这种状态时,即使一次尝试失败,断路器也会立即进入打开状态。 如果尝试成功,断路器将进入关闭状态,在这种情况下,它不会再次进入打开状态,直到再次发生配置的连续故障次数。 任何成功的尝试都会将状态重置为零失败,以确定断路器何时可以再次进入打开状态。
通常,此建议可用于外部服务,在这些服务中,可能需要一些时间才能失败,例如尝试建立网络连接的超时。
这RequestHandlerCircuitBreakerAdvice
有两个属性:threshold
和halfOpenAfter
.
这threshold
属性表示断路器打开之前需要发生的连续故障数。
它默认为5
.
这halfOpenAfter
属性表示断路器在尝试另一个请求之前等待的最后一次失败后的时间。
默认值为 1000 毫秒。
以下示例配置断路器并显示其DEBUG
和ERROR
输出:
<int:service-activator input-channel="input" ref="failer" method="service">
<int:request-handler-advice-chain>
<bean class="o.s.i.handler.advice.RequestHandlerCircuitBreakerAdvice">
<property name="threshold" value="2" />
<property name="halfOpenAfter" value="12000" />
</bean>
</int:request-handler-advice-chain>
</int:service-activator>
05.617 DEBUG [task-scheduler-1]preSend on channel 'input', message: [Payload=...]
05.638 ERROR [task-scheduler-1]org.springframework.messaging.MessageHandlingException: java.lang.RuntimeException: foo
...
10.598 DEBUG [task-scheduler-2]preSend on channel 'input', message: [Payload=...]
10.600 ERROR [task-scheduler-2]org.springframework.messaging.MessageHandlingException: java.lang.RuntimeException: foo
...
15.598 DEBUG [task-scheduler-3]preSend on channel 'input', message: [Payload=...]
15.599 ERROR [task-scheduler-3]org.springframework.messaging.MessagingException: Circuit Breaker is Open for ServiceActivator
...
20.598 DEBUG [task-scheduler-2]preSend on channel 'input', message: [Payload=...]
20.598 ERROR [task-scheduler-2]org.springframework.messaging.MessagingException: Circuit Breaker is Open for ServiceActivator
...
25.598 DEBUG [task-scheduler-5]preSend on channel 'input', message: [Payload=...]
25.601 ERROR [task-scheduler-5]org.springframework.messaging.MessageHandlingException: java.lang.RuntimeException: foo
...
30.598 DEBUG [task-scheduler-1]preSend on channel 'input', message: [Payload=foo...]
30.599 ERROR [task-scheduler-1]org.springframework.messaging.MessagingException: Circuit Breaker is Open for ServiceActivator
在前面的示例中,阈值设置为2
和halfOpenAfter
设置为12
秒。 每 5 秒到达一次新请求。前两次尝试调用了服务。第三次和第四次失败,异常指示断路器已打开。尝试了第五次请求,因为请求是在上次失败后 15 秒。第六次尝试立即失败,因为断路器立即打开。
表达式评估建议
最后提供的建议类是o.s.i.handler.advice.ExpressionEvaluatingRequestHandlerAdvice
. 此建议比其他两个建议更通用。它提供了一种机制来评估发送到端点的原始入站消息的表达式。在成功或失败后,可以评估单独的表达式。(可选)可以将包含评估结果的消息与输入消息一起发送到消息通道。
此建议的典型用例可能是使用<ftp:outbound-channel-adapter/>
,如果传输成功,则可能将文件移动到一个目录,如果传输失败,则将文件移动到另一个目录:
通知具有用于设置成功时表达式、失败表达式以及每个表达式的相应通道的属性。对于成功案例,发送到successChannel
是一个AdviceMessage
,有效负载是表达式计算的结果。一个附加属性,称为inputMessage
,包含发送到处理程序的原始消息。发送到failureChannel
(当处理程序抛出异常时)是ErrorMessage
有效负载为MessageHandlingExpressionEvaluatingAdviceException
. 像所有人一样MessagingException
实例中,此有效负载具有failedMessage
和cause
属性,以及名为evaluationResult
,其中包含表达式计算的结果。
从 5.1.3 版开始,如果配置了通道,但未提供表达式,则默认表达式用于计算为payload 消息的。 |
在通知的作用域中抛出异常时,默认情况下,该异常会在任何之后抛出给调用者failureExpression
被评估。如果希望禁止抛出异常,请将trapException
属性设置为true
. 以下建议显示如何配置advice
使用 Java DSL:
@SpringBootApplication
public class EerhaApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(EerhaApplication.class, args);
MessageChannel in = context.getBean("advised.input", MessageChannel.class);
in.send(new GenericMessage<>("good"));
in.send(new GenericMessage<>("bad"));
context.close();
}
@Bean
public IntegrationFlow advised() {
return f -> f.<String>handle((payload, headers) -> {
if (payload.equals("good")) {
return null;
}
else {
throw new RuntimeException("some failure");
}
}, c -> c.advice(expressionAdvice()));
}
@Bean
public Advice expressionAdvice() {
ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
advice.setSuccessChannelName("success.input");
advice.setOnSuccessExpressionString("payload + ' was successful'");
advice.setFailureChannelName("failure.input");
advice.setOnFailureExpressionString(
"payload + ' was bad, with reason: ' + #exception.cause.message");
advice.setTrapException(true);
return advice;
}
@Bean
public IntegrationFlow success() {
return f -> f.handle(System.out::println);
}
@Bean
public IntegrationFlow failure() {
return f -> f.handle(System.out::println);
}
}
速率限制器建议
速率限制器建议 (RateLimiterRequestHandlerAdvice
) 允许确保端点不会因请求而过载。当违反速率限制时,请求将处于阻止状态。
此建议的一个典型用例可能是外部服务提供商不允许超过n
每分钟的请求数。
这RateLimiterRequestHandlerAdvice
实现完全基于 Resilience4j 项目,并且需要RateLimiter
或RateLimiterConfig
注射。 也可以配置默认值和/或自定义名称。
以下示例配置了每 1 秒一个请求的速率限制器通知:
@Bean
public RateLimiterRequestHandlerAdvice rateLimiterRequestHandlerAdvice() {
return new RateLimiterRequestHandlerAdvice(RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofSeconds(1))
.limitForPeriod(1)
.build());
}
@ServiceActivator(inputChannel = "requestChannel", outputChannel = "resultChannel",
adviceChain = "rateLimiterRequestHandlerAdvice")
public String handleRequest(String payload) {
...
}
缓存建议
从 5.2 版开始,CacheRequestHandlerAdvice
已经引入。它基于 Spring Framework 中的缓存抽象,并与@Caching
注释系列。内部逻辑基于CacheAspectSupport
扩展,其中缓存作的代理是围绕AbstractReplyProducingMessageHandler.RequestHandler.handleRequestMessage
方法与请求Message<?>
作为参数。此通知可以使用 SpEL 表达式或Function
以评估缓存键。请求Message<?>
可用作 SpEL 评估上下文的根对象,或作为Function
input 参数。默认情况下,payload
的请求消息用于缓存键。 这CacheRequestHandlerAdvice
必须配置为cacheNames
,当默认缓存作为CacheableOperation
,或使用任何任意的集合CacheOperation
s. 每CacheOperation
可以单独配置或具有共享选项,例如CacheManager
,CacheResolver
和CacheErrorHandler
,可以从CacheRequestHandlerAdvice
配置。 此配置功能类似于 Spring Framework 的@CacheConfig
和@Caching
注释组合。
如果CacheManager
,则默认情况下从BeanFactory
在CacheAspectSupport
.
以下示例使用不同的缓存作集配置两个通知:
@Bean
public CacheRequestHandlerAdvice cacheAdvice() {
CacheRequestHandlerAdvice cacheRequestHandlerAdvice = new CacheRequestHandlerAdvice(TEST_CACHE);
cacheRequestHandlerAdvice.setKeyExpressionString("payload");
return cacheRequestHandlerAdvice;
}
@Transformer(inputChannel = "transformerChannel", outputChannel = "nullChannel", adviceChain = "cacheAdvice")
public Object transform(Message<?> message) {
...
}
@Bean
public CacheRequestHandlerAdvice cachePutAndEvictAdvice() {
CacheRequestHandlerAdvice cacheRequestHandlerAdvice = new CacheRequestHandlerAdvice();
cacheRequestHandlerAdvice.setKeyExpressionString("payload");
CachePutOperation.Builder cachePutBuilder = new CachePutOperation.Builder();
cachePutBuilder.setCacheName(TEST_PUT_CACHE);
CacheEvictOperation.Builder cacheEvictBuilder = new CacheEvictOperation.Builder();
cacheEvictBuilder.setCacheName(TEST_CACHE);
cacheRequestHandlerAdvice.setCacheOperations(cachePutBuilder.build(), cacheEvictBuilder.build());
return cacheRequestHandlerAdvice;
}
@ServiceActivator(inputChannel = "serviceChannel", outputChannel = "nullChannel",
adviceChain = "cachePutAndEvictAdvice")
public Message<?> service(Message<?> message) {
...
}