非Spring Boot的Spring应用中Resilience4j注解重试不生效求助
在非Spring Boot Spring应用中使用Resilience4j注解实现重试的正确配置
明确结论:非Spring Boot的Spring应用完全可以使用Resilience4j的注解实现重试,你的配置缺少注解驱动的AOP支持配置,这是重试未触发的核心原因。以下是修正后的完整实现步骤:
1. 补充依赖(确保AOP相关依赖齐全)
除已引入的resilience4j-retry和resilience4j-spring,还需添加Spring AOP与AspectJ Weaver依赖,保证切面能正常拦截方法调用:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>你的Spring对应版本</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-retry</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring</artifactId> <version>1.7.1</version> </dependency>
2. 手动配置Resilience4j注解支持Bean
非Spring Boot不会自动装配Resilience4j的切面,需手动配置重试规则、重试实例及切面处理器:
import io.github.resilience4j.retry.Retry; import io.github.resilience4j.retry.RetryConfig; import io.github.resilience4j.spring.annotation.RetryAspect; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import java.time.Duration; @Configuration @EnableAspectJAutoProxy // 必须开启AspectJ自动代理,让重试切面生效 public class Resilience4jConfig { @Bean public RetryConfig retryConfig() { return RetryConfig.custom() .maxAttempts(10) .waitDuration(Duration.ofMillis(1000)) .retryExceptions(EmptyStackException.class) // 指定触发重试的异常类型 .build(); } @Bean(name = "id") // 此处name必须与@Retry注解的name完全匹配 public Retry retry(RetryConfig retryConfig) { return Retry.of("id", retryConfig); } @Bean public RetryAspect retryAspect() { return new RetryAspect(); // 注册重试切面,处理@Retry注解逻辑 } }
3. 服务层方法的正确使用
确保服务类被Spring容器管理(添加@Service注解),且@Retry注解的name与配置的Retry Bean名称一致:
import io.github.resilience4j.spring.annotation.Retry; import org.springframework.stereotype.Service; @Service public class TestService { @Retry(name = "id") // 名称需与配置中Retry Bean的name严格匹配 public void testRetry() { System.out.println("执行方法,时间:" + System.currentTimeMillis()); throw new EmptyStackException(); } }
关键注意事项
- 必须添加
@EnableAspectJAutoProxy注解,开启Spring的AOP代理能力,否则Resilience4j切面无法拦截方法调用。 - Retry Bean的
name属性要和@Retry注解中的name完全一致,否则注解无法找到对应的重试规则。 - 确保抛出的异常是
EmptyStackException(或其子类),且已在RetryConfig中配置为触发重试的异常。 - 服务类必须由Spring容器托管,不能手动new实例,否则AOP无法生效。
内容的提问来源于stack exchange,提问作者s.bhardwaj
相关产品推荐
相关产品推荐

