spring AOP切入点不适用于Feign客户端

332nm8kg  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(211)

在我的项目中,我有一个Feign客户端扩展了从OpenAPI规范生成的API接口:

@FeignClient(name = "customerClient", url = "${spring.microservice.tenant-service-gateway.host}", configuration = FeignConfiguration.class)
public interface CustomerClient extends CustomersApi {

}

字符串
FeignConfiguration引入了500响应代码的重试配置:

@Configuration
@EnableAspectJAutoProxy
public class FeignConfiguration {

    @Bean
    public Retryer httpResponseCodeRetryer(
            @Value("${feign.max-attempt-count}") int retryCount,
            @Value("${feign.retry-period-seconds}") int retryPeriod
    ) {
        return new Retryer.Default(TimeUnit.SECONDS.toMillis(retryPeriod), TimeUnit.SECONDS.toMillis(3L), retryCount);
    }

    @Bean
    public ErrorDecoder httpCodeErrorDecoder() {
        return new HttpCodeErrorDecoder();
    }

    static class HttpCodeErrorDecoder implements ErrorDecoder {

        @Override
        public Exception decode(String methodKey, Response response) {
            var exception = feign.FeignException.errorStatus(methodKey, response);
            int status = response.status();
            if (status == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return new RetryableException(
                        response.status(),
                        exception.getMessage(),
                        response.request().httpMethod(),
                        exception,
                        null,
                        response.request());
            }
            return exception;
        }
    }
}


我想要的是为202响应代码添加重试功能。为了实现这一点,我添加了这个切入点:

@Aspect
public class AfterReturningExample {

    @Around("execution(* com.project.client.CustomerClient.*(..))")
    public Object customerClient(ProceedingJoinPoint pjp) throws Throwable {
        var proceed = pjp.proceed();
        //some logic here
        return proceed;
    }
}


我尝试通过为CustomersApi的方法添加切入点来解决这个问题,如下所示:

@Around("execution(* com.project.api.CustomersApi+.*(..))")
public Object customerApi(ProceedingJoinPoint pjp) throws Throwable {
  var proceed = pjp.proceed();
  //some logic here
  return proceed;
}

xdnvmnnf

xdnvmnnf1#

如果你的类上只有一个@Aspect,它将不会被检测到,因此不会应用任何东西,因为Spring AOP看不到它。
您可以将@Component添加到您的@Aspect注解类中,这将使其可用于Spring。

@Component
@Aspect
public class AfterReturningExample { ... }

字符串
另一种选择是在@ComponentScan中写入includeFilter,以包含所有用@Aspect注解的类。

@SpringBootApplication
@ComponentScan(includeFilter= { @Filter(type = FilterType.ANNOTATION, value=org.aspectj.lang.annotation.Aspect )}


这样,用@Aspect(而不是@Component)注解的类也将被包括在内。
两种方法都行。

相关问题