diff --git a/README.md b/README.md index 2440c35..2a53a00 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ retrofit: - response_status_not_2xx - occur_io_exception # 重试拦截器 - retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor + retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.RetryInterceptor # 熔断降级配置 degrade: @@ -487,7 +487,7 @@ retrofit: global-retry-rules: - response_status_not_2xx # 重试拦截器 - retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor + retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.RetryInterceptor ``` **重试规则支持三种配置**: diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/Intercept.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/Intercept.java index 086be14..caba97d 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/Intercept.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/Intercept.java @@ -1,10 +1,13 @@ package com.github.lianjiatech.retrofit.spring.boot.annotation; +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor; -import java.lang.annotation.*; - /** * 自动将注解上的参数值赋值到handleInterceptor实例上 * Automatically assign the parameter value on the annotation to the handleInterceptor instance diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/OkHttpClientBuilder.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/OkHttpClientBuilder.java index 1d52077..212fe9e 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/OkHttpClientBuilder.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/OkHttpClientBuilder.java @@ -1,6 +1,10 @@ package com.github.lianjiatech.retrofit.spring.boot.annotation; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * @author 陈添明 @@ -8,5 +12,4 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented -public @interface OkHttpClientBuilder { -} +public @interface OkHttpClientBuilder {} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitClient.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitClient.java index 187a4c8..1a7cf72 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitClient.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitClient.java @@ -1,16 +1,18 @@ package com.github.lianjiatech.retrofit.spring.boot.annotation; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + import com.github.lianjiatech.retrofit.spring.boot.core.DefaultErrorDecoder; import com.github.lianjiatech.retrofit.spring.boot.core.ErrorDecoder; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogLevel; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogStrategy; -import org.springframework.stereotype.Service; + import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; -import java.lang.annotation.*; - /** * @author 陈添明 */ @@ -74,33 +76,6 @@ Class fallbackFactory() default void.class; - /** - * 针对当前接口是否启用日志打印 - * Whether to enable log printing for the current interface - * - * @return enableLog - */ - boolean enableLog() default true; - - /** - * 日志打印级别,支持的日志级别参见{@link LogLevel} - * 如果为NULL,则取全局日志打印级别 - * Log printing level, see {@link LogLevel} for supported log levels - * - * @return logLevel - */ - LogLevel logLevel() default LogLevel.NULL; - - /** - * 日志打印策略,支持的日志打印策略参见{@link LogStrategy} - * 如果为NULL,则取全局日志打印策略 - * Log printing strategy, see {@link LogStrategy} for supported log printing strategies - * - * @return logStrategy - */ - LogStrategy logStrategy() default LogStrategy.NULL; - - /** * When calling {@link Retrofit#create(Class)} on the resulting {@link Retrofit} instance, eagerly validate the * configuration of all methods in the supplied interface. diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitScan.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitScan.java index 2e0d0dc..7c8aca4 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitScan.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/annotation/RetrofitScan.java @@ -1,9 +1,14 @@ package com.github.lianjiatech.retrofit.spring.boot.annotation; -import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClientScannerRegistrar; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + import org.springframework.context.annotation.Import; -import java.lang.annotation.*; +import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClientScannerRegistrar; /** * @author 陈添明 @@ -22,7 +27,6 @@ */ String[] value() default {}; - /** * Scan package path * @@ -30,7 +34,6 @@ */ String[] basePackages() default {}; - /** * Scan package classes * diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/LogProperty.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/LogProperty.java index 9d3cd96..a9299b9 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/LogProperty.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/LogProperty.java @@ -1,9 +1,7 @@ package com.github.lianjiatech.retrofit.spring.boot.config; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.BaseLoggingInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogLevel; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogStrategy; +import com.github.lianjiatech.retrofit.spring.boot.log.LogLevel; +import com.github.lianjiatech.retrofit.spring.boot.log.LogStrategy; import lombok.Data; @@ -14,10 +12,10 @@ public class LogProperty { /** - * 启用日志打印 + * 是否启用全局日志打印 * Enable log printing */ - private boolean enable = true; + private boolean enableGlobalLog = true; /** * 全局日志打印级别,支持的日志级别参见{@link LogLevel} @@ -30,10 +28,4 @@ public class LogProperty { * Log printing strategy, see {@link LogStrategy} for supported log printing strategies */ private LogStrategy globalLogStrategy = LogStrategy.BASIC; - - /** - * 日志打印拦截器 - * Log print Interceptor - */ - private Class loggingInterceptor = DefaultLoggingInterceptor.class; } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitAutoConfiguration.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitAutoConfiguration.java index 36bd564..1d24e1e 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitAutoConfiguration.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitAutoConfiguration.java @@ -5,7 +5,6 @@ import java.util.Map; import java.util.concurrent.TimeUnit; -import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; @@ -26,23 +25,22 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github.lianjiatech.retrofit.spring.boot.core.AutoConfiguredRetrofitScannerRegistrar; import com.github.lianjiatech.retrofit.spring.boot.core.NoValidServiceInstanceChooser; -import com.github.lianjiatech.retrofit.spring.boot.core.PrototypeInterceptorBdfProcessor; +import com.github.lianjiatech.retrofit.spring.boot.core.PathMatchInterceptorBdfProcessor; import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitFactoryBean; import com.github.lianjiatech.retrofit.spring.boot.core.ServiceInstanceChooser; import com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser; import com.github.lianjiatech.retrofit.spring.boot.degrade.DegradeInterceptor; import com.github.lianjiatech.retrofit.spring.boot.degrade.ResourceNameParser; import com.github.lianjiatech.retrofit.spring.boot.degrade.sentinel.SentinelDegradeInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.interceptor.ErrorDecoderInterceptor; import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor; import com.github.lianjiatech.retrofit.spring.boot.interceptor.NetworkInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.ServiceInstanceChooserInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.retry.BaseRetryInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.util.ApplicationContextUtils; +import com.github.lianjiatech.retrofit.spring.boot.interceptor.ServiceChooseInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.log.LoggingInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.retry.RetryInterceptor; import lombok.extern.slf4j.Slf4j; import okhttp3.ConnectionPool; -import retrofit2.CallAdapter; -import retrofit2.Converter; import retrofit2.converter.jackson.JacksonConverterFactory; /** @@ -66,8 +64,8 @@ public RetrofitAutoConfiguration(RetrofitProperties retrofitProperties) { public static class RetrofitProcessorAutoConfiguration { @Bean - public static PrototypeInterceptorBdfProcessor prototypeInterceptorBdfProcessor() { - return new PrototypeInterceptorBdfProcessor(); + public static PathMatchInterceptorBdfProcessor prototypeInterceptorBdfProcessor() { + return new PathMatchInterceptorBdfProcessor(); } } @@ -76,13 +74,19 @@ public static PrototypeInterceptorBdfProcessor prototypeInterceptorBdfProcessor( public RetrofitConfigBean retrofitConfigBean(@Autowired(required = false) ResourceNameParser resourceNameParser, @Autowired(required = false) DegradeInterceptor degradeInterceptor, @Autowired(required = false) List globalInterceptors, - @Autowired(required = false) List networkInterceptors) - throws IllegalAccessException, InstantiationException { + @Autowired(required = false) List networkInterceptors, + ServiceChooseInterceptor serviceChooseInterceptor, RetryInterceptor retryInterceptor, + LoggingInterceptor loggingInterceptor, ErrorDecoderInterceptor errorDecoderInterceptor) { + RetrofitConfigBean retrofitConfigBean = new RetrofitConfigBean(retrofitProperties); retrofitConfigBean.setGlobalInterceptors(globalInterceptors); retrofitConfigBean.setNetworkInterceptors(networkInterceptors); retrofitConfigBean.setResourceNameParser(resourceNameParser); retrofitConfigBean.setDegradeInterceptor(degradeInterceptor); + retrofitConfigBean.setServiceChooseInterceptor(serviceChooseInterceptor); + retrofitConfigBean.setRetryInterceptor(retryInterceptor); + retrofitConfigBean.setLoggingInterceptor(loggingInterceptor); + retrofitConfigBean.setErrorDecoderInterceptor(errorDecoderInterceptor); Map poolRegistry = new HashMap<>(4); retrofitProperties.getPool().forEach((poolName, poolConfig) -> { @@ -93,39 +97,39 @@ public RetrofitConfigBean retrofitConfigBean(@Autowired(required = false) Resour poolRegistry.put(poolName, connectionPool); }); retrofitConfigBean.setPoolRegistry(poolRegistry); + retrofitConfigBean.setGlobalCallAdapterFactoryClasses(retrofitProperties.getGlobalCallAdapterFactories()); + retrofitConfigBean.setGlobalConverterFactoryClasses(retrofitProperties.getGlobalConverterFactories()); + return retrofitConfigBean; + } - // callAdapterFactory - Class[] globalCallAdapterFactories = - retrofitProperties.getGlobalCallAdapterFactories(); - retrofitConfigBean.setGlobalCallAdapterFactoryClasses(globalCallAdapterFactories); - - // converterFactory - Class[] globalConverterFactories = - retrofitProperties.getGlobalConverterFactories(); - retrofitConfigBean.setGlobalConverterFactoryClasses(globalConverterFactories); - - // retryInterceptor - RetryProperty retry = retrofitProperties.getRetry(); - Class retryInterceptor = retry.getRetryInterceptor(); - BaseRetryInterceptor retryInterceptorInstance = - ApplicationContextUtils.getBeanOrNew(applicationContext, retryInterceptor); - BeanUtils.copyProperties(retry, retryInterceptorInstance); - retrofitConfigBean.setRetryInterceptor(retryInterceptorInstance); - - // add ServiceInstanceChooserInterceptor - ServiceInstanceChooser serviceInstanceChooser; - try { - serviceInstanceChooser = applicationContext.getBean(ServiceInstanceChooser.class); - } catch (BeansException e) { - serviceInstanceChooser = new NoValidServiceInstanceChooser(); - } + @Bean + @ConditionalOnMissingBean + public ErrorDecoderInterceptor errorDecoderInterceptor() { + return new ErrorDecoderInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + public RetryInterceptor retryInterceptor() { + return new RetryInterceptor(retrofitProperties.getRetry()); + } - ServiceInstanceChooserInterceptor serviceInstanceChooserInterceptor = - new ServiceInstanceChooserInterceptor(serviceInstanceChooser); - retrofitConfigBean.setServiceInstanceChooserInterceptor(serviceInstanceChooserInterceptor); + @Bean + @ConditionalOnMissingBean + public LoggingInterceptor logInterceptor() { + return new LoggingInterceptor(retrofitProperties.getLog()); + } + @Bean + @ConditionalOnMissingBean + public ServiceInstanceChooser serviceInstanceChooser() { + return new NoValidServiceInstanceChooser(); + } - return retrofitConfigBean; + @Bean + @ConditionalOnMissingBean + ServiceChooseInterceptor serviceChooseInterceptor(@Autowired ServiceInstanceChooser serviceInstanceChooser) { + return new ServiceChooseInterceptor(serviceInstanceChooser); } @Bean diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitConfigBean.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitConfigBean.java index 348c3ba..f7b5016 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitConfigBean.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitConfigBean.java @@ -6,10 +6,12 @@ import com.github.lianjiatech.retrofit.spring.boot.degrade.DegradeInterceptor; import com.github.lianjiatech.retrofit.spring.boot.degrade.ResourceNameParser; +import com.github.lianjiatech.retrofit.spring.boot.interceptor.ErrorDecoderInterceptor; import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor; import com.github.lianjiatech.retrofit.spring.boot.interceptor.NetworkInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.ServiceInstanceChooserInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.retry.BaseRetryInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.interceptor.ServiceChooseInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.log.LoggingInterceptor; +import com.github.lianjiatech.retrofit.spring.boot.retry.RetryInterceptor; import lombok.Data; import okhttp3.ConnectionPool; @@ -30,9 +32,9 @@ public class RetrofitConfigBean { private List networkInterceptors; - private BaseRetryInterceptor retryInterceptor; + private RetryInterceptor retryInterceptor; - private ServiceInstanceChooserInterceptor serviceInstanceChooserInterceptor; + private ServiceChooseInterceptor serviceChooseInterceptor; private Class[] globalConverterFactoryClasses; @@ -42,6 +44,10 @@ public class RetrofitConfigBean { private DegradeInterceptor degradeInterceptor; + private LoggingInterceptor loggingInterceptor; + + private ErrorDecoderInterceptor errorDecoderInterceptor; + public RetrofitConfigBean(RetrofitProperties retrofitProperties) { this.retrofitProperties = retrofitProperties; } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetryProperty.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetryProperty.java index 4f7d337..673dc62 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetryProperty.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetryProperty.java @@ -1,7 +1,5 @@ package com.github.lianjiatech.retrofit.spring.boot.config; -import com.github.lianjiatech.retrofit.spring.boot.retry.BaseRetryInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor; import com.github.lianjiatech.retrofit.spring.boot.retry.RetryRule; import lombok.Data; @@ -20,8 +18,8 @@ public class RetryProperty { private boolean enableGlobalRetry = false; /** - * 全局最大重试次数,最大可设置为100 - * The maximum number of retries, the maximum can be set to 100 + * 全局最大重试次数 + * The maximum number of retries */ private int globalMaxRetries = 2; @@ -37,9 +35,4 @@ public class RetryProperty { */ private RetryRule[] globalRetryRules = {RetryRule.RESPONSE_STATUS_NOT_2XX, RetryRule.OCCUR_IO_EXCEPTION}; - - /** - * retry interceptor - */ - private Class retryInterceptor = DefaultRetryInterceptor.class; } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/AutoConfiguredRetrofitScannerRegistrar.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/AutoConfiguredRetrofitScannerRegistrar.java index e432288..776f6c9 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/AutoConfiguredRetrofitScannerRegistrar.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/AutoConfiguredRetrofitScannerRegistrar.java @@ -1,6 +1,5 @@ package com.github.lianjiatech.retrofit.spring.boot.core; - import java.util.List; import org.springframework.beans.BeansException; @@ -24,7 +23,8 @@ * @author 陈添明 */ @Slf4j -public class AutoConfiguredRetrofitScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware { +public class AutoConfiguredRetrofitScannerRegistrar + implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware { private BeanFactory beanFactory; @@ -51,7 +51,8 @@ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, B packages.forEach(pkg -> log.debug("Using auto-configuration base package '{}'", pkg)); } - // Scan the @RetrofitClient annotated interface under the specified path and register it to the BeanDefinitionRegistry + // Scan the @RetrofitClient annotated interface under the specified path and register it to the + // BeanDefinitionRegistry ClassPathRetrofitClientScanner scanner = new ClassPathRetrofitClientScanner(registry, classLoader); if (resourceLoader != null) { scanner.setResourceLoader(resourceLoader); diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BasicTypeConverterFactory.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BasicTypeConverterFactory.java index fab4f83..2cfb93b 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BasicTypeConverterFactory.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BasicTypeConverterFactory.java @@ -1,26 +1,25 @@ package com.github.lianjiatech.retrofit.spring.boot.core; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.math.BigDecimal; - /** * @author 陈添明 */ public final class BasicTypeConverterFactory extends Converter.Factory { @Override - public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { + public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, + Annotation[] methodAnnotations, Retrofit retrofit) { return null; } - @Override public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (String.class.getTypeName().equals(type.getTypeName())) { @@ -41,7 +40,6 @@ public Converter requestBodyConverter(Type type, Annotation[] pa } - private static final class StringResponseConverter implements Converter { @Override diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BodyCallAdapterFactory.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BodyCallAdapterFactory.java index f974de2..3319de1 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BodyCallAdapterFactory.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/BodyCallAdapterFactory.java @@ -1,31 +1,32 @@ /* * Copyright (C) 2015 Square, Inc. * - * 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 + * 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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. + * 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.github.lianjiatech.retrofit.spring.boot.core; -import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitException; -import okhttp3.Request; -import okhttp3.ResponseBody; -import retrofit2.*; - import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Objects; import java.util.concurrent.CompletableFuture; +import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitException; + +import okhttp3.Request; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.CallAdapter; +import retrofit2.Converter; +import retrofit2.Response; +import retrofit2.Retrofit; /** * 同步调用,如果返回的http状态码是是成功,返回responseBody 反序列化之后的对象。否则,抛出异常!异常信息中包含请求和响应相关信息。 diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ErrorDecoder.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ErrorDecoder.java index 4c5772f..f53e07d 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ErrorDecoder.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ErrorDecoder.java @@ -1,11 +1,12 @@ package com.github.lianjiatech.retrofit.spring.boot.core; +import java.io.IOException; + import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitException; + import okhttp3.Request; import okhttp3.Response; -import java.io.IOException; - /** * 错误解码器。ErrorDecoder. * 当请求发生异常或者收到无效响应结果的时候,将HTTP相关信息解码到异常中,无效响应由业务自己判断 @@ -32,7 +33,6 @@ default RuntimeException invalidRespDecode(Request request, Response response) { return null; } - /** * 当请求发生IO异常时,将HTTP信息解码到异常中。 * When an IO exception occurs in the request, the HTTP information is decoded into the exception. diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/NoValidServiceInstanceChooser.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/NoValidServiceInstanceChooser.java index 12d338e..a0f9ed5 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/NoValidServiceInstanceChooser.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/NoValidServiceInstanceChooser.java @@ -1,15 +1,14 @@ package com.github.lianjiatech.retrofit.spring.boot.core; -import com.github.lianjiatech.retrofit.spring.boot.exception.ServiceInstanceChooseException; - import java.net.URI; +import com.github.lianjiatech.retrofit.spring.boot.exception.ServiceInstanceChooseException; + /** * @author 陈添明 */ public class NoValidServiceInstanceChooser implements ServiceInstanceChooser { - /** * Chooses a ServiceInstance URI from the LoadBalancer for the specified service. * diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PrototypeInterceptorBdfProcessor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PathMatchInterceptorBdfProcessor.java similarity index 86% rename from src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PrototypeInterceptorBdfProcessor.java rename to src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PathMatchInterceptorBdfProcessor.java index cb4c3d4..67b02b9 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PrototypeInterceptorBdfProcessor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/PathMatchInterceptorBdfProcessor.java @@ -1,6 +1,5 @@ package com.github.lianjiatech.retrofit.spring.boot.core; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.PrototypeInterceptor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; @@ -8,11 +7,13 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor; + /** * @author 陈添明 */ -public class PrototypeInterceptorBdfProcessor implements BeanDefinitionRegistryPostProcessor { +public class PathMatchInterceptorBdfProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { @@ -25,7 +26,7 @@ public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) t } try { Class beanClass = Class.forName(beanClassName); - if (PrototypeInterceptor.class.isAssignableFrom(beanClass)) { + if (BasePathMatchInterceptor.class.isAssignableFrom(beanClass)) { beanDefinition.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE); } } catch (ClassNotFoundException e) { diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ResponseCallAdapterFactory.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ResponseCallAdapterFactory.java index bc9bd2d..9f5a282 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ResponseCallAdapterFactory.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ResponseCallAdapterFactory.java @@ -1,34 +1,32 @@ /* * Copyright (C) 2015 Square, Inc. * - * 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 + * 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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. + * 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.github.lianjiatech.retrofit.spring.boot.core; -import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitException; -import okhttp3.Request; -import org.springframework.util.Assert; -import retrofit2.Call; -import retrofit2.CallAdapter; -import retrofit2.Response; -import retrofit2.Retrofit; - import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Objects; +import org.springframework.util.Assert; + +import com.github.lianjiatech.retrofit.spring.boot.exception.RetrofitException; + +import okhttp3.Request; +import retrofit2.Call; +import retrofit2.CallAdapter; +import retrofit2.Response; +import retrofit2.Retrofit; /** *

@@ -48,9 +46,9 @@ public final class ResponseCallAdapterFactory extends CallAdapter.Factory { return null; } - final class ResponseCallAdapter implements CallAdapter> { + static final class ResponseCallAdapter implements CallAdapter> { - private Type returnType; + private final Type returnType; ResponseCallAdapter(Type returnType) { this.returnType = returnType; @@ -58,13 +56,12 @@ final class ResponseCallAdapter implements CallAdapter> { @Override public Type responseType() { - ParameterizedType parameterizedType = (ParameterizedType) returnType; + ParameterizedType parameterizedType = (ParameterizedType)returnType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); Assert.notEmpty(actualTypeArguments, "Response must specify generic parameters!"); return actualTypeArguments[0]; } - @Override public Response adapt(Call call) { Request request = call.request(); diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitClientScannerRegistrar.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitClientScannerRegistrar.java index bc846ed..668bc1a 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitClientScannerRegistrar.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitClientScannerRegistrar.java @@ -1,6 +1,9 @@ package com.github.lianjiatech.retrofit.spring.boot.core; -import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitScan; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; + import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ResourceLoaderAware; @@ -12,14 +15,13 @@ import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; +import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitScan; /** * @author 陈添明 */ -public class RetrofitClientScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware { +public class RetrofitClientScannerRegistrar + implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware { private ResourceLoader resourceLoader; @@ -32,7 +34,8 @@ public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionR if (attributes == null) { return; } - // Scan the @RetrofitClient annotated interface under the specified path and register it to the BeanDefinitionRegistry + // Scan the @RetrofitClient annotated interface under the specified path and register it to the + // BeanDefinitionRegistry ClassPathRetrofitClientScanner scanner = new ClassPathRetrofitClientScanner(registry, classLoader); if (resourceLoader != null) { scanner.setResourceLoader(resourceLoader); @@ -44,7 +47,6 @@ public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionR scanner.doScan(basePackages); } - /** * 获取扫描的基础包路径 * @@ -64,16 +66,14 @@ private String[] getPackagesToScan(AnnotationAttributes attributes) { for (Class basePackageClass : basePackageClasses) { packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); } - return packagesToScan.toArray(new String[packagesToScan.size()]); + return packagesToScan.toArray(new String[0]); } - @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } - @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitFactoryBean.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitFactoryBean.java index 53f3219..ef283ca 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitFactoryBean.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitFactoryBean.java @@ -1,7 +1,6 @@ package com.github.lianjiatech.retrofit.spring.boot.core; import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -32,24 +31,15 @@ import com.github.lianjiatech.retrofit.spring.boot.annotation.OkHttpClientBuilder; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.config.DegradeProperty; -import com.github.lianjiatech.retrofit.spring.boot.config.LogProperty; import com.github.lianjiatech.retrofit.spring.boot.config.RetrofitConfigBean; import com.github.lianjiatech.retrofit.spring.boot.config.RetrofitProperties; import com.github.lianjiatech.retrofit.spring.boot.degrade.DegradeProxy; import com.github.lianjiatech.retrofit.spring.boot.degrade.DegradeType; import com.github.lianjiatech.retrofit.spring.boot.degrade.FallbackFactory; import com.github.lianjiatech.retrofit.spring.boot.degrade.sentinel.SentinelDegrade; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.BaseLoggingInterceptor; import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.ErrorDecoderInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogLevel; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogStrategy; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.NetworkInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.ServiceInstanceChooserInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.retry.BaseRetryInterceptor; import com.github.lianjiatech.retrofit.spring.boot.util.AnnotationExtendUtils; -import com.github.lianjiatech.retrofit.spring.boot.util.ApplicationContextUtils; +import com.github.lianjiatech.retrofit.spring.boot.util.AppContextUtils; import com.github.lianjiatech.retrofit.spring.boot.util.BeanExtendUtils; import com.github.lianjiatech.retrofit.spring.boot.util.RetrofitUtils; @@ -172,7 +162,7 @@ private void checkRetrofitInterface() { if (!void.class.isAssignableFrom(fallbackClass)) { Assert.isTrue(retrofitInterface.isAssignableFrom(fallbackClass), "The fallback type must implement the current interface!the fallback type is " + fallbackClass); - Object fallback = ApplicationContextUtils.getBeanOrNull(applicationContext, fallbackClass); + Object fallback = AppContextUtils.getBeanOrNull(applicationContext, fallbackClass); Assert.notNull(fallback, "fallback must be a valid spring bean! the fallback class is " + fallbackClass); } @@ -181,7 +171,7 @@ private void checkRetrofitInterface() { Assert.isTrue(FallbackFactory.class.isAssignableFrom(fallbackFactoryClass), "The fallback factory type must implement FallbackFactory!the fallback factory is " + fallbackFactoryClass); - Object fallbackFactory = ApplicationContextUtils.getBeanOrNull(applicationContext, fallbackFactoryClass); + Object fallbackFactory = AppContextUtils.getBeanOrNull(applicationContext, fallbackFactoryClass); Assert.notNull(fallbackFactory, "fallback factory must be a valid spring bean! the fallback factory class is " + fallbackFactoryClass); @@ -210,92 +200,22 @@ private okhttp3.ConnectionPool parseConnectionPool() { } private OkHttpClient createOkHttpClient() - throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + throws IllegalAccessException, InstantiationException, InvocationTargetException { OkHttpClient.Builder okHttpClientBuilder = createOkHttpClientBuilder(); RetrofitClient retrofitClient = retrofitInterface.getAnnotation(RetrofitClient.class); - addDegradeInterceptor(okHttpClientBuilder); - addServiceInstanceChooserInterceptor(okHttpClientBuilder, retrofitClient); - addErrorDecoderInterceptor(okHttpClientBuilder, retrofitClient); - addDefineOnInterfaceInterceptor(okHttpClientBuilder); - addGlobalInterceptor(okHttpClientBuilder); - addRetryInterceptor(okHttpClientBuilder); - addLoggingInterceptor(okHttpClientBuilder, retrofitClient); - addNetworkInterceptor(okHttpClientBuilder); - return okHttpClientBuilder.build(); - } - - private void addNetworkInterceptor(OkHttpClient.Builder okHttpClientBuilder) { - List networkInterceptors = retrofitConfigBean.getNetworkInterceptors(); - if (!CollectionUtils.isEmpty(networkInterceptors)) { - for (NetworkInterceptor networkInterceptor : networkInterceptors) { - okHttpClientBuilder.addNetworkInterceptor(networkInterceptor); - } - } - } - - private void addLoggingInterceptor(OkHttpClient.Builder okHttpClientBuilder, RetrofitClient retrofitClient) - throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - LogProperty logProperty = retrofitProperties.getLog(); - if (logProperty.isEnable() && retrofitClient.enableLog()) { - Class loggingInterceptorClass = logProperty.getLoggingInterceptor(); - Constructor constructor = - loggingInterceptorClass.getConstructor(LogLevel.class, LogStrategy.class); - LogLevel logLevel = retrofitClient.logLevel(); - LogStrategy logStrategy = retrofitClient.logStrategy(); - if (logLevel.equals(LogLevel.NULL)) { - logLevel = logProperty.getGlobalLogLevel(); - } - if (logStrategy.equals(LogStrategy.NULL)) { - logStrategy = logProperty.getGlobalLogStrategy(); - } - - Assert.isTrue(!logLevel.equals(LogLevel.NULL), "LogLevel cannot all be configured as LogLevel.NULL!"); - Assert.isTrue(!logStrategy.equals(LogStrategy.NULL), - "logStrategy cannot all be configured as LogStrategy.NULL!"); - - BaseLoggingInterceptor loggingInterceptor = constructor.newInstance(logLevel, logStrategy); - okHttpClientBuilder.addInterceptor(loggingInterceptor); - } - } - - private void addRetryInterceptor(OkHttpClient.Builder okHttpClientBuilder) { - BaseRetryInterceptor retryInterceptor = retrofitConfigBean.getRetryInterceptor(); - okHttpClientBuilder.addInterceptor(retryInterceptor); - } - - private void addGlobalInterceptor(OkHttpClient.Builder okHttpClientBuilder) { - List globalInterceptors = retrofitConfigBean.getGlobalInterceptors(); - globalInterceptors.forEach(okHttpClientBuilder::addInterceptor); - } - - private void addDefineOnInterfaceInterceptor(OkHttpClient.Builder okHttpClientBuilder) - throws InstantiationException, IllegalAccessException { - findInterceptorByAnnotation().forEach(okHttpClientBuilder::addInterceptor); - } - - private void addErrorDecoderInterceptor(OkHttpClient.Builder okHttpClientBuilder, RetrofitClient retrofitClient) - throws InstantiationException, IllegalAccessException { - Class errorDecoderClass = retrofitClient.errorDecoder(); - ErrorDecoder decoder = ApplicationContextUtils.getBeanOrNew(applicationContext, errorDecoderClass); - ErrorDecoderInterceptor decoderInterceptor = ErrorDecoderInterceptor.create(decoder); - okHttpClientBuilder.addInterceptor(decoderInterceptor); - } - - private void addServiceInstanceChooserInterceptor(OkHttpClient.Builder okHttpClientBuilder, - RetrofitClient retrofitClient) { - if (StringUtils.hasText(retrofitClient.serviceId())) { - ServiceInstanceChooserInterceptor serviceInstanceChooserInterceptor = - retrofitConfigBean.getServiceInstanceChooserInterceptor(); - if (serviceInstanceChooserInterceptor != null) { - okHttpClientBuilder.addInterceptor(serviceInstanceChooserInterceptor); - } - } - } - - private void addDegradeInterceptor(OkHttpClient.Builder okHttpClientBuilder) { if (isEnableSentinelDegrade(retrofitProperties.getDegrade(), retrofitInterface)) { okHttpClientBuilder.addInterceptor(retrofitConfigBean.getDegradeInterceptor()); } + if (StringUtils.hasText(retrofitClient.serviceId())) { + okHttpClientBuilder.addInterceptor(retrofitConfigBean.getServiceChooseInterceptor()); + } + okHttpClientBuilder.addInterceptor(retrofitConfigBean.getErrorDecoderInterceptor()); + findInterceptorByAnnotation().forEach(okHttpClientBuilder::addInterceptor); + retrofitConfigBean.getGlobalInterceptors().forEach(okHttpClientBuilder::addInterceptor); + okHttpClientBuilder.addInterceptor(retrofitConfigBean.getRetryInterceptor()); + okHttpClientBuilder.addInterceptor(retrofitConfigBean.getLoggingInterceptor()); + retrofitConfigBean.getNetworkInterceptors().forEach(okHttpClientBuilder::addInterceptor); + return okHttpClientBuilder.build(); } private OkHttpClient.Builder createOkHttpClientBuilder() throws InvocationTargetException, IllegalAccessException { @@ -369,8 +289,8 @@ private List findInterceptorByAnnotation() Class interceptorClass = (Class)handler; BasePathMatchInterceptor interceptor = - ApplicationContextUtils.getTargetInstanceIfNecessary( - ApplicationContextUtils.getBeanOrNew(applicationContext, interceptorClass)); + AppContextUtils.getTargetInstanceIfNecessary( + AppContextUtils.getBeanOrNew(applicationContext, interceptorClass)); Map annotationResolveAttributes = new HashMap<>(8); // 占位符属性替换。Placeholder attribute replacement annotationAttributes.forEach((key, value) -> { @@ -446,7 +366,7 @@ private List getCallAdapterFactories( for (Class callAdapterFactoryClass : combineCallAdapterFactoryClasses) { CallAdapter.Factory callAdapterFactory = CALL_ADAPTER_FACTORIES_CACHE.get(callAdapterFactoryClass); if (callAdapterFactory == null) { - callAdapterFactory = ApplicationContextUtils.getBeanOrNew(applicationContext, callAdapterFactoryClass); + callAdapterFactory = AppContextUtils.getBeanOrNew(applicationContext, callAdapterFactoryClass); CALL_ADAPTER_FACTORIES_CACHE.put(callAdapterFactoryClass, callAdapterFactory); } callAdapterFactories.add(callAdapterFactory); @@ -476,10 +396,7 @@ private List getConverterFactories(Class converterFactoryClass : combineConverterFactoryClasses) { Converter.Factory converterFactory = CONVERTER_FACTORIES_CACHE.get(converterFactoryClass); if (converterFactory == null) { - converterFactory = ApplicationContextUtils.getBeanOrNull(applicationContext, converterFactoryClass); - if (converterFactory == null) { - converterFactory = converterFactoryClass.newInstance(); - } + converterFactory = AppContextUtils.getBeanOrNew(applicationContext, converterFactoryClass); CONVERTER_FACTORIES_CACHE.put(converterFactoryClass, converterFactory); } converterFactories.add(converterFactory); diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ServiceInstanceChooser.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ServiceInstanceChooser.java index d88f31f..9394915 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ServiceInstanceChooser.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/ServiceInstanceChooser.java @@ -8,7 +8,6 @@ @FunctionalInterface public interface ServiceInstanceChooser { - /** * Chooses a ServiceInstance URI from the LoadBalancer for the specified service. * diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/DegradeProxy.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/DegradeProxy.java index b991bf0..42206ff 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/DegradeProxy.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/DegradeProxy.java @@ -7,7 +7,7 @@ import org.springframework.context.ApplicationContext; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; -import com.github.lianjiatech.retrofit.spring.boot.util.ApplicationContextUtils; +import com.github.lianjiatech.retrofit.spring.boot.util.AppContextUtils; /** * @author 陈添明 @@ -27,13 +27,13 @@ public static T create(Object source, Class retrofitInterface, Applicatio Class fallbackClass = retrofitClient.fallback(); Object fallback = null; if (!void.class.isAssignableFrom(fallbackClass)) { - fallback = ApplicationContextUtils.getBeanOrNull(applicationContext, fallbackClass); + fallback = AppContextUtils.getBeanOrNull(applicationContext, fallbackClass); } Class fallbackFactoryClass = retrofitClient.fallbackFactory(); FallbackFactory fallbackFactory = null; if (!void.class.isAssignableFrom(fallbackFactoryClass)) { fallbackFactory = - (FallbackFactory)ApplicationContextUtils.getBeanOrNull(applicationContext, fallbackFactoryClass); + (FallbackFactory)AppContextUtils.getBeanOrNull(applicationContext, fallbackFactoryClass); } DegradeProxy degradeProxy = new DegradeProxy(source, fallback, fallbackFactory); return (T)Proxy.newProxyInstance(retrofitInterface.getClassLoader(), diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/FallbackFactory.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/FallbackFactory.java index e6b9c17..931c5a5 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/FallbackFactory.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/FallbackFactory.java @@ -6,7 +6,6 @@ */ public interface FallbackFactory { - /** * Returns an instance of the fallback appropriate for the given cause * diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitException.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitException.java index 8a1d822..a591fd7 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitException.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitException.java @@ -1,18 +1,19 @@ package com.github.lianjiatech.retrofit.spring.boot.exception; +import java.io.IOException; + +import org.springframework.util.StringUtils; + import com.github.lianjiatech.retrofit.spring.boot.util.RetrofitUtils; + import okhttp3.Request; import okhttp3.Response; -import org.springframework.util.StringUtils; - -import java.io.IOException; /** * @author 陈添明 */ public class RetrofitException extends RuntimeException { - public RetrofitException(String message, Throwable cause) { super(message, cause); } @@ -21,7 +22,6 @@ public RetrofitException(String message) { super(message); } - public static RetrofitException errorStatus(Request request, Response response) { String msg = String.format("invalid Response! request=%s, response=%s", request, response); try { @@ -30,7 +30,8 @@ public static RetrofitException errorStatus(Request request, Response response) msg += ", body=" + responseBody; } } catch (ReadResponseBodyException e) { - throw new RetrofitException(String.format("read ResponseBody error! request=%s, response=%s", request, response), e); + throw new RetrofitException( + String.format("read ResponseBody error! request=%s, response=%s", request, response), e); } finally { response.close(); } @@ -43,7 +44,7 @@ public static RetrofitException errorExecuting(Request request, IOException caus public static RetrofitException errorUnknown(Request request, Exception cause) { if (cause instanceof RetrofitException) { - return (RetrofitException) cause; + return (RetrofitException)cause; } return new RetrofitException(cause.getMessage() + ", request=" + request, cause); } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitIOException.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitIOException.java index 478cf08..8113da5 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitIOException.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/exception/RetrofitIOException.java @@ -5,7 +5,6 @@ */ public class RetrofitIOException extends RetrofitException { - public RetrofitIOException(String message, Throwable cause) { super(message, cause); } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BaseLoggingInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BaseLoggingInterceptor.java deleted file mode 100644 index 6781d62..0000000 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BaseLoggingInterceptor.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.interceptor; - -import okhttp3.Interceptor; - -/** - * @author 陈添明 - */ -public abstract class BaseLoggingInterceptor implements Interceptor { - - /** - * 日志打印级别 - * Log printing level - */ - protected final LogLevel logLevel; - - /** - * 日志打印策略 - * Log printing strategy - */ - protected final LogStrategy logStrategy; - - - public BaseLoggingInterceptor(LogLevel logLevel, LogStrategy logStrategy) { - this.logLevel = logLevel; - this.logStrategy = logStrategy; - } -} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BasePathMatchInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BasePathMatchInterceptor.java index 715b297..07a478b 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BasePathMatchInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/BasePathMatchInterceptor.java @@ -6,6 +6,7 @@ import org.springframework.util.PathMatcher; import lombok.Data; +import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; @@ -15,7 +16,7 @@ * @author 陈添明 */ @Data -public abstract class BasePathMatchInterceptor implements PrototypeInterceptor { +public abstract class BasePathMatchInterceptor implements Interceptor { private String[] include; diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/DefaultLoggingInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/DefaultLoggingInterceptor.java deleted file mode 100644 index 4cbb829..0000000 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/DefaultLoggingInterceptor.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.interceptor; - -import java.io.IOException; - -import lombok.extern.slf4j.Slf4j; -import okhttp3.Response; -import okhttp3.logging.HttpLoggingInterceptor; - -/** - * @author 陈添明 - */ -@Slf4j -public class DefaultLoggingInterceptor extends BaseLoggingInterceptor { - - private final HttpLoggingInterceptor httpLoggingInterceptor; - - public DefaultLoggingInterceptor(LogLevel logLevel, LogStrategy logStrategy) { - super(logLevel, logStrategy); - HttpLoggingInterceptor.Logger logger = httpLoggingInterceptorLogger(logLevel); - httpLoggingInterceptor = new HttpLoggingInterceptor(logger); - String name = logStrategy.name(); - HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.valueOf(name); - httpLoggingInterceptor.setLevel(level); - } - - @Override - public Response intercept(Chain chain) throws IOException { - return httpLoggingInterceptor.intercept(chain); - } - - - public HttpLoggingInterceptor.Logger httpLoggingInterceptorLogger(LogLevel level) { - if (level == LogLevel.DEBUG) { - return log::debug; - } else if (level == LogLevel.ERROR) { - return log::error; - } else if (level == LogLevel.INFO) { - return log::info; - } else if (level == LogLevel.WARN) { - return log::warn; - } - throw new UnsupportedOperationException("We don't support this log level currently."); - } -} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ErrorDecoderInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ErrorDecoderInterceptor.java index 2587922..2b4f0d5 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ErrorDecoderInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ErrorDecoderInterceptor.java @@ -1,31 +1,38 @@ package com.github.lianjiatech.retrofit.spring.boot.interceptor; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +import java.lang.reflect.Method; +import java.util.Objects; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.core.ErrorDecoder; +import com.github.lianjiatech.retrofit.spring.boot.util.AppContextUtils; +import lombok.SneakyThrows; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; +import retrofit2.Invocation; /** * @author 陈添明 */ -public class ErrorDecoderInterceptor implements Interceptor { - - private final ErrorDecoder errorDecoder; - - private static final Map CACHE = new HashMap<>(4); +public class ErrorDecoderInterceptor implements Interceptor, ApplicationContextAware { - private ErrorDecoderInterceptor(ErrorDecoder errorDecoder) { - this.errorDecoder = errorDecoder; - } + protected ApplicationContext applicationContext; @Override + @SneakyThrows public Response intercept(Chain chain) throws IOException { Request request = chain.request(); + Method method = Objects.requireNonNull(request.tag(Invocation.class)).method(); + RetrofitClient retrofitClient = method.getDeclaringClass().getAnnotation(RetrofitClient.class); + ErrorDecoder errorDecoder = + AppContextUtils.getBeanOrNew(applicationContext, retrofitClient.errorDecoder()); boolean decoded = false; try { Response response = chain.proceed(request); @@ -51,13 +58,8 @@ public Response intercept(Chain chain) throws IOException { } } - public static ErrorDecoderInterceptor create(ErrorDecoder errorDecoder) { - ErrorDecoderInterceptor interceptor = CACHE.get(errorDecoder); - if (interceptor != null) { - return interceptor; - } - interceptor = new ErrorDecoderInterceptor(errorDecoder); - CACHE.put(errorDecoder, interceptor); - return interceptor; + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; } } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/GlobalInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/GlobalInterceptor.java index 45ebe87..c0eaaf1 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/GlobalInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/GlobalInterceptor.java @@ -6,6 +6,4 @@ * * @author 陈添明 */ -public interface GlobalInterceptor extends Interceptor { - -} +public interface GlobalInterceptor extends Interceptor {} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogLevel.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogLevel.java deleted file mode 100644 index 95ef984..0000000 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogLevel.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.interceptor; - -/** - * @author 陈添明 - */ -public enum LogLevel { - - /** - * No config - */ - NULL, - - ERROR, - - WARN, - - INFO, - - DEBUG, -} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/NetworkInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/NetworkInterceptor.java index 737fb47..f672478 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/NetworkInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/NetworkInterceptor.java @@ -5,5 +5,4 @@ /** * @author 陈添明 */ -public interface NetworkInterceptor extends Interceptor { -} +public interface NetworkInterceptor extends Interceptor {} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/PrototypeInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/PrototypeInterceptor.java deleted file mode 100644 index 3e600a9..0000000 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/PrototypeInterceptor.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.interceptor; - - -import okhttp3.Interceptor; - -/** - * 拦截器标记接口 - * 该接口的实现类在spring容器中的scope会自动修改为prototype - * Interceptor marking interface - * The scope of the implementation class of this interface in the spring container will be automatically modified to prototype - * - * @author 陈添明 - */ -public interface PrototypeInterceptor extends Interceptor { -} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceInstanceChooserInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceChooseInterceptor.java similarity index 83% rename from src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceInstanceChooserInterceptor.java rename to src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceChooseInterceptor.java index 6f1b997..32b5ebb 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceInstanceChooserInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/ServiceChooseInterceptor.java @@ -1,35 +1,36 @@ package com.github.lianjiatech.retrofit.spring.boot.interceptor; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Objects; + +import org.springframework.util.StringUtils; + import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.core.ServiceInstanceChooser; + import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; -import org.springframework.util.StringUtils; import retrofit2.Invocation; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URI; - /** * @author 陈添明 */ -public class ServiceInstanceChooserInterceptor implements Interceptor { +public class ServiceChooseInterceptor implements Interceptor { private final ServiceInstanceChooser serviceInstanceChooser; - public ServiceInstanceChooserInterceptor(ServiceInstanceChooser serviceDiscovery) { + public ServiceChooseInterceptor(ServiceInstanceChooser serviceDiscovery) { this.serviceInstanceChooser = serviceDiscovery; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); - Invocation invocation = request.tag(Invocation.class); - assert invocation != null; - Method method = invocation.method(); + Method method = Objects.requireNonNull(request.tag(Invocation.class)).method(); Class declaringClass = method.getDeclaringClass(); RetrofitClient retrofitClient = declaringClass.getAnnotation(RetrofitClient.class); String baseUrl = retrofitClient.baseUrl(); diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogLevel.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogLevel.java new file mode 100644 index 0000000..78b874d --- /dev/null +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogLevel.java @@ -0,0 +1,17 @@ +package com.github.lianjiatech.retrofit.spring.boot.log; + +/** + * @author 陈添明 + */ +public enum LogLevel { + + ERROR, + + WARN, + + INFO, + + DEBUG, + + TRACE, +} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogStrategy.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogStrategy.java similarity index 78% rename from src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogStrategy.java rename to src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogStrategy.java index a2ad088..0ab720e 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogStrategy.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LogStrategy.java @@ -1,4 +1,4 @@ -package com.github.lianjiatech.retrofit.spring.boot.interceptor; +package com.github.lianjiatech.retrofit.spring.boot.log; /** @@ -7,11 +7,6 @@ public enum LogStrategy { - /** - * No config - */ - NULL, - /** * No logs. */ diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/Logging.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/Logging.java new file mode 100644 index 0000000..66d4932 --- /dev/null +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/Logging.java @@ -0,0 +1,38 @@ +package com.github.lianjiatech.retrofit.spring.boot.log; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author 陈添明 + * @since 2022/4/30 9:47 下午 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +@Documented +public @interface Logging { + + /** + * 是否启用日志打印,针对当前接口或者方法 + */ + boolean enable() default true; + + /** + * 日志打印级别,支持的日志级别参见{@link LogLevel} + * 如果为NULL,则取全局日志打印级别 + * Log printing level, see {@link LogLevel} for supported log levels + * + */ + LogLevel logLevel() default LogLevel.INFO; + + /** + * 日志打印策略,支持的日志打印策略参见{@link LogStrategy} + * 如果为NULL,则取全局日志打印策略 + * Log printing strategy, see {@link LogStrategy} for supported log printing strategies + * + */ + LogStrategy logStrategy() default LogStrategy.BASIC; +} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LoggingInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LoggingInterceptor.java new file mode 100644 index 0000000..cd8f0cc --- /dev/null +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/log/LoggingInterceptor.java @@ -0,0 +1,81 @@ +package com.github.lianjiatech.retrofit.spring.boot.log; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Objects; + +import com.github.lianjiatech.retrofit.spring.boot.config.LogProperty; + +import lombok.extern.slf4j.Slf4j; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; +import retrofit2.Invocation; + +/** + * @author 陈添明 + * @since 2022/4/30 8:21 下午 + */ +@Slf4j +public class LoggingInterceptor implements Interceptor { + + private final LogProperty logProperty; + + public LoggingInterceptor(LogProperty logProperty) { + this.logProperty = logProperty; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + Method method = Objects.requireNonNull(request.tag(Invocation.class)).method(); + // 获取重试配置 + Logging logging = method.getDeclaringClass().getAnnotation(Logging.class); + if (!needLog(logging)) { + return chain.proceed(request); + } + LogLevel logLevel = logging == null ? logProperty.getGlobalLogLevel() : logging.logLevel(); + LogStrategy logStrategy = logging == null ? logProperty.getGlobalLogStrategy() : logging.logStrategy(); + HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(matchLogger(logLevel)); + httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.valueOf(logStrategy.name())); + return httpLoggingInterceptor.intercept(chain); + } + + protected boolean needLog(Logging logging) { + if (logProperty.isEnableGlobalLog()) { + // 开启全局打印日志的情况下 + // 没配置@Logging,需要重试 + if (logging == null) { + return true; + } + // 配置了@Logging,enable==true,需要打印日志 + if (logging.enable()) { + return true; + } + } else { + // 未开启全局日志打印 + // 配置了@Logging,enable==true,需要打印日志 + if (logging != null && logging.enable()) { + return true; + } + } + // 其他情况,不需要打印日志 + return false; + } + + protected HttpLoggingInterceptor.Logger matchLogger(LogLevel level) { + if (level == LogLevel.DEBUG) { + return log::debug; + } else if (level == LogLevel.ERROR) { + return log::error; + } else if (level == LogLevel.INFO) { + return log::info; + } else if (level == LogLevel.WARN) { + return log::warn; + } else if (level == LogLevel.TRACE) { + return log::trace; + } + throw new UnsupportedOperationException("We don't support this log level currently."); + } +} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/BaseRetryInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/BaseRetryInterceptor.java deleted file mode 100644 index a0db314..0000000 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/BaseRetryInterceptor.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.retry; - -import java.io.IOException; -import java.lang.reflect.Method; - -import com.github.lianjiatech.retrofit.spring.boot.util.AnnotationExtendUtils; - -import lombok.Data; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Invocation; - -/** - * 请求重试拦截器 - * Request retry interceptor - * - * @author 陈添明 - */ -@Data -public abstract class BaseRetryInterceptor implements Interceptor { - - private boolean enableGlobalRetry; - - private int globalMaxRetries; - - private int globalIntervalMs; - - private RetryRule[] globalRetryRules; - - private static final int LIMIT_RETRIES = 100; - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - Invocation invocation = request.tag(Invocation.class); - assert invocation != null; - Method method = invocation.method(); - // 获取重试配置 - Retry retry = AnnotationExtendUtils.findAnnotation(method, Retry.class); - - if (!needRetry(retry)) { - return chain.proceed(request); - } - - // 重试 - int maxRetries = retry == null ? globalMaxRetries : retry.maxRetries(); - int intervalMs = retry == null ? globalIntervalMs : retry.intervalMs(); - RetryRule[] retryRules = retry == null ? globalRetryRules : retry.retryRules(); - // 最多重试100次 - maxRetries = Math.min(maxRetries, LIMIT_RETRIES); - return retryIntercept(maxRetries, intervalMs, retryRules, chain); - - } - - private boolean needRetry(Retry retry) { - - if (enableGlobalRetry) { - // 开启全局重试的情况下 - // 没配置@Retry,需要重试 - if (retry == null) { - return true; - } - // 配置了@Retry,enable==true,需要重试 - if (retry.enable()) { - return true; - } - } else { - // 未开启全局重试 - // 配置了@Retry,enable==true,需要重试 - if (retry != null && retry.enable()) { - return true; - } - } - return false; - } - - /** - * 重试拦截 - * - * @param maxRetries 最大重试次数。Maximum number of retries - * @param intervalMs 重试时间间隔。Retry interval - * @param retryRules 重试规则。Retry rules - * @param chain 执行链。Execution chain - * @return 请求响应。Response - */ - protected abstract Response retryIntercept(int maxRetries, int intervalMs, RetryRule[] retryRules, Chain chain); -} diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/DefaultRetryInterceptor.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryInterceptor.java similarity index 53% rename from src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/DefaultRetryInterceptor.java rename to src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryInterceptor.java index 9ac72a1..5d723f9 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/DefaultRetryInterceptor.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryInterceptor.java @@ -1,21 +1,73 @@ package com.github.lianjiatech.retrofit.spring.boot.retry; import java.io.IOException; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; +import java.util.Objects; import java.util.stream.Collectors; +import com.github.lianjiatech.retrofit.spring.boot.config.RetryProperty; +import com.github.lianjiatech.retrofit.spring.boot.util.AnnotationExtendUtils; + +import lombok.Data; import lombok.extern.slf4j.Slf4j; +import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; +import retrofit2.Invocation; /** * @author 陈添明 */ @Slf4j -public class DefaultRetryInterceptor extends BaseRetryInterceptor { +@Data +public class RetryInterceptor implements Interceptor { + + private final RetryProperty retryProperty; + + public RetryInterceptor(RetryProperty retryProperty) { + this.retryProperty = retryProperty; + } @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + Method method = Objects.requireNonNull(request.tag(Invocation.class)).method(); + // 获取重试配置 + Retry retry = AnnotationExtendUtils.findAnnotation(method, Retry.class); + if (!needRetry(retry)) { + return chain.proceed(request); + } + // 重试 + int maxRetries = retry == null ? retryProperty.getGlobalMaxRetries() : retry.maxRetries(); + int intervalMs = retry == null ? retryProperty.getGlobalIntervalMs() : retry.intervalMs(); + RetryRule[] retryRules = retry == null ? retryProperty.getGlobalRetryRules() : retry.retryRules(); + return retryIntercept(maxRetries, intervalMs, retryRules, chain); + } + + protected boolean needRetry(Retry retry) { + + if (retryProperty.isEnableGlobalRetry()) { + // 开启全局重试的情况下 + // 没配置@Retry,需要重试 + if (retry == null) { + return true; + } + // 配置了@Retry,enable==true,需要重试 + if (retry.enable()) { + return true; + } + } else { + // 未开启全局重试 + // 配置了@Retry,enable==true,需要重试 + if (retry != null && retry.enable()) { + return true; + } + } + return false; + } + protected Response retryIntercept(int maxRetries, int intervalMs, RetryRule[] retryRules, Chain chain) { HashSet retryRuleSet = (HashSet)Arrays.stream(retryRules).collect(Collectors.toSet()); RetryStrategy retryStrategy = new RetryStrategy(maxRetries, intervalMs); @@ -52,7 +104,7 @@ protected Response retryIntercept(int maxRetries, int intervalMs, RetryRule[] re } } - private boolean shouldThrowEx(HashSet retryRuleSet, Exception e) { + protected boolean shouldThrowEx(HashSet retryRuleSet, Exception e) { if (retryRuleSet.contains(RetryRule.OCCUR_EXCEPTION)) { return false; } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryRule.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryRule.java index 1bb2722..19842a0 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryRule.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/retry/RetryRule.java @@ -24,5 +24,4 @@ public enum RetryRule { * IO exception occurred */ OCCUR_IO_EXCEPTION, - } diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AnnotationExtendUtils.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AnnotationExtendUtils.java index cbfc9cd..4553334 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AnnotationExtendUtils.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AnnotationExtendUtils.java @@ -3,8 +3,6 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import org.springframework.lang.Nullable; - import lombok.experimental.UtilityClass; /** @@ -21,7 +19,7 @@ public class AnnotationExtendUtils { * @param 注解泛型参数 * @return 方法或者类上指定的注解。 */ - public static A findAnnotation(Method method, @Nullable Class annotationType) { + public static A findAnnotation(Method method, Class annotationType) { A annotation = method.getAnnotation(annotationType); if (annotation != null) { return annotation; diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/ApplicationContextUtils.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AppContextUtils.java similarity index 83% rename from src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/ApplicationContextUtils.java rename to src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AppContextUtils.java index 082adae..ee2a23b 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/ApplicationContextUtils.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/AppContextUtils.java @@ -11,7 +11,7 @@ * @author 陈添明 */ @UtilityClass -public final class ApplicationContextUtils { +public final class AppContextUtils { public static T getBeanOrNull(ApplicationContext context, Class clz) { try { @@ -21,6 +21,14 @@ public static T getBeanOrNull(ApplicationContext context, Class clz) { } } + public static T getBeanOrDefault(ApplicationContext context, Class clz, T t) { + try { + return context.getBean(clz); + } catch (BeansException e) { + return t; + } + } + public static T getBeanOrNew(ApplicationContext context, Class clz) throws InstantiationException, IllegalAccessException { try { diff --git a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/RetrofitUtils.java b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/RetrofitUtils.java index 26aa06e..2421a48 100644 --- a/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/RetrofitUtils.java +++ b/src/main/java/com/github/lianjiatech/retrofit/spring/boot/util/RetrofitUtils.java @@ -79,7 +79,6 @@ public static String readResponseBody(Response response) throws ReadResponseBody } } - private static boolean bodyHasUnknownEncoding(Headers headers) { String contentEncoding = headers.get(CONTENT_ENCODING); return contentEncoding != null @@ -87,7 +86,6 @@ private static boolean bodyHasUnknownEncoding(Headers headers) { && !GZIP.equalsIgnoreCase(contentEncoding); } - public static String convertBaseUrl(RetrofitClient retrofitClient, String baseUrl, Environment environment) { if (StringUtils.hasText(baseUrl)) { baseUrl = environment.resolveRequiredPlaceholders(baseUrl); @@ -107,4 +105,3 @@ public static String convertBaseUrl(RetrofitClient retrofitClient, String baseUr return baseUrl; } } - diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DegradeTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DegradeTest.java index cdb1b0b..dbbde48 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DegradeTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DegradeTest.java @@ -25,7 +25,6 @@ /** * @author 陈添明 - * @summary * @since 2022/1/21 4:20 下午 */ @SpringBootTest(classes = RetrofitTestApplication.class) diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DownloadTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DownloadTest.java index 4489f52..5453dbe 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DownloadTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/DownloadTest.java @@ -1,18 +1,20 @@ package com.github.lianjiatech.retrofit.spring.boot.test; -import com.github.lianjiatech.retrofit.spring.boot.test.http.DownloadApi; -import okhttp3.ResponseBody; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.util.UUID; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import retrofit2.Response; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.util.UUID; +import com.github.lianjiatech.retrofit.spring.boot.test.http.DownloadApi; + +import okhttp3.ResponseBody; +import retrofit2.Response; /** * @author 陈添明 @@ -47,7 +49,7 @@ public void download() throws Exception { int length; while ((length = is.read(b)) > 0) { fos.write(b, 0, length); - } + } is.close(); fos.close(); } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ErrorDecoderTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ErrorDecoderTest.java index d67648b..8d160dd 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ErrorDecoderTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ErrorDecoderTest.java @@ -33,8 +33,9 @@ public class ErrorDecoderTest { private MockWebServer server; - private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); + private static final ObjectMapper objectMapper = + new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); @Before public void before() throws IOException { @@ -50,7 +51,6 @@ public void after() throws IOException { server.close(); } - @Test(expected = Throwable.class) public void test() throws JsonProcessingException { // mock @@ -75,5 +75,4 @@ public void test() throws JsonProcessingException { } - } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/InterceptTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/InterceptTest.java index 300cd14..a1a3503 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/InterceptTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/InterceptTest.java @@ -1,13 +1,7 @@ package com.github.lianjiatech.retrofit.spring.boot.test; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; -import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; -import com.github.lianjiatech.retrofit.spring.boot.test.http.InterceptApi; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import java.io.IOException; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -17,11 +11,18 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import java.io.IOException; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; +import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; +import com.github.lianjiatech.retrofit.spring.boot.test.http.InterceptApi; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; /** * @author 陈添明 - * @summary * @since 2022/1/21 4:20 下午 */ @SpringBootTest(classes = RetrofitTestApplication.class) @@ -31,9 +32,9 @@ public class InterceptTest { @Autowired private InterceptApi interceptApi; - private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); - + private static final ObjectMapper objectMapper = + new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); private MockWebServer server; diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitConvertFactoriesTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitConvertFactoriesTest.java index ea7bcfb..503d6e0 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitConvertFactoriesTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitConvertFactoriesTest.java @@ -49,7 +49,6 @@ public void after() throws IOException { server.close(); } - @Test public void test() { @@ -76,5 +75,4 @@ public void test() { Assert.assertEquals(10, data.getAge().intValue()); } - } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitExceptionTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitExceptionTest.java index 910a52a..630934c 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitExceptionTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitExceptionTest.java @@ -32,9 +32,9 @@ public class RetrofitExceptionTest { @Autowired private HttpApi httpApi; - private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); - + private static final ObjectMapper objectMapper = + new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); private MockWebServer server; @@ -52,7 +52,6 @@ public void after() throws IOException { server.close(); } - @Test(expected = Throwable.class) // @Test public void testHttpResponseFailure() throws IOException { diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitStarterTest.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitStarterTest.java index 1f6de73..fc465d4 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitStarterTest.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitStarterTest.java @@ -46,7 +46,6 @@ @Slf4j public class RetrofitStarterTest { - @Autowired private HttpApi httpApi; @@ -62,9 +61,9 @@ public class RetrofitStarterTest { @Autowired private DownloadApi downloadApi; - private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); - + private static final ObjectMapper objectMapper = + new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); private MockWebServer server; @@ -82,7 +81,6 @@ public void after() throws IOException { server.close(); } - @Test public void testGetPersonBody() throws Exception { @@ -141,7 +139,6 @@ public void testRetrofitConfigRef() throws IOException { Assert.assertEquals(10, data2.getAge().intValue()); } - @Test public void testRetCall() throws InterruptedException, IOException { // mock @@ -159,7 +156,6 @@ public void testRetCall() throws InterruptedException, IOException { .setBody(objectMapper.writeValueAsString(mockResult)); server.enqueue(response); - Call> resultCall = httpApi.getPersonCall(2L); CountDownLatch countDownLatch = new CountDownLatch(1); // 异步回调处理 @@ -194,7 +190,6 @@ public void onFailure(Call> call, Throwable t) { countDownLatch.await(); } - @Test public void testFuture() throws ExecutionException, InterruptedException, IOException { @@ -361,7 +356,6 @@ public void testMap() throws IOException { System.out.println(stringMapMap); } - @Test public void savePersonList() throws IOException { @@ -389,7 +383,6 @@ public void savePersonList() throws IOException { Assert.assertEquals(code, 0); } - @Test public void testString() { diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitTestApplication.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitTestApplication.java index b96bc11..fb17afd 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitTestApplication.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/RetrofitTestApplication.java @@ -3,6 +3,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; + import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.jaxb.JaxbConverterFactory; @@ -16,7 +17,6 @@ public static void main(String[] args) { SpringApplication.run(RetrofitTestApplication.class, args); } - @Bean GsonConverterFactory gsonConverterFactory() { return GsonConverterFactory.create(); diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Person.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Person.java index 46bd902..d8e79b2 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Person.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Person.java @@ -1,8 +1,13 @@ package com.github.lianjiatech.retrofit.spring.boot.test.entity; +import lombok.Data; +import lombok.experimental.Accessors; + /** * @author 陈添明 */ +@Data +@Accessors(chain = true) public class Person { private Long id; @@ -10,40 +15,4 @@ public class Person { private String name; private Integer age; - - public Long getId() { - return id; - } - - public Person setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Person setName(String name) { - this.name = name; - return this; - } - - public Integer getAge() { - return age; - } - - public Person setAge(Integer age) { - this.age = age; - return this; - } - - @Override - public String toString() { - return "Person{" + - "id=" + id + - ", name='" + name + '\'' + - ", age=" + age + - '}'; - } } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Result.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Result.java index e3d1c56..59e806a 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Result.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/entity/Result.java @@ -2,61 +2,18 @@ import java.io.Serializable; +import lombok.Data; +import lombok.experimental.Accessors; + /** * @author 陈添明 */ +@Data +@Accessors(chain = true) public class Result implements Serializable { - private static final long serialVersionUID = -504027247149928390L; - private int code; private String msg; private String exceptionMsg; private T data; - - public int getCode() { - return code; - } - - public Result setCode(int code) { - this.code = code; - return this; - } - - public String getMsg() { - return msg; - } - - public Result setMsg(String msg) { - this.msg = msg; - return this; - } - - public String getExceptionMsg() { - return exceptionMsg; - } - - public Result setExceptionMsg(String exceptionMsg) { - this.exceptionMsg = exceptionMsg; - return this; - } - - public T getData() { - return data; - } - - public Result setData(T data) { - this.data = data; - return this; - } - - @Override - public String toString() { - return "Result{" + - "code=" + code + - ", msg='" + msg + '\'' + - ", exceptionMsg='" + exceptionMsg + '\'' + - ", data=" + data + - '}'; - } } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppException.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppException.java index e353b04..d574714 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppException.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppException.java @@ -10,8 +10,7 @@ public class AppException extends RuntimeException { * detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ - public AppException() { - } + public AppException() {} /** * Constructs a new runtime exception with the specified detail message. diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppIOException.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppIOException.java index a92c0e5..a1f3258 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppIOException.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/ex/AppIOException.java @@ -10,8 +10,7 @@ public class AppIOException extends RuntimeException { * detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ - public AppIOException() { - } + public AppIOException() {} /** * Constructs a new runtime exception with the specified detail message. diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ConvertFactoriesTestApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ConvertFactoriesTestApi.java index 8f9b3b4..10c2613 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ConvertFactoriesTestApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ConvertFactoriesTestApi.java @@ -3,6 +3,7 @@ import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; + import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.jaxb.JaxbConverterFactory; import retrofit2.http.GET; @@ -11,7 +12,8 @@ /** * @author 陈添明 */ -@RetrofitClient(baseUrl = "${test.baseUrl}", converterFactories = {GsonConverterFactory.class, JaxbConverterFactory.class}) +@RetrofitClient(baseUrl = "${test.baseUrl}", + converterFactories = {GsonConverterFactory.class, JaxbConverterFactory.class}) public interface ConvertFactoriesTestApi { @GET("person") diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/DegradeApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/DegradeApi.java index 49ae5d3..b8c8ccb 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/DegradeApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/DegradeApi.java @@ -10,7 +10,6 @@ /** * @author 陈添明 - * @summary * @since 2022/1/21 4:19 下午 */ @RetrofitClient(baseUrl = "${test.baseUrl}") diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ErrorDecoderTestApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ErrorDecoderTestApi.java index ef66176..66872dd 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ErrorDecoderTestApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/ErrorDecoderTestApi.java @@ -1,24 +1,21 @@ package com.github.lianjiatech.retrofit.spring.boot.test.http; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; -import com.github.lianjiatech.retrofit.spring.boot.interceptor.LogStrategy; +import com.github.lianjiatech.retrofit.spring.boot.log.LogStrategy; +import com.github.lianjiatech.retrofit.spring.boot.log.Logging; import com.github.lianjiatech.retrofit.spring.boot.test.InvalidRespErrorDecoder; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; + import retrofit2.http.Body; import retrofit2.http.POST; /** * @author 陈添明 */ -@RetrofitClient(baseUrl = "${test.baseUrl}", logStrategy = LogStrategy.BODY, errorDecoder = InvalidRespErrorDecoder.class) +@Logging(logStrategy = LogStrategy.BODY) +@RetrofitClient(baseUrl = "${test.baseUrl}", errorDecoder = InvalidRespErrorDecoder.class) public interface ErrorDecoderTestApi { - /** - * . - * - * @param person . - * @return . - */ @POST("error") Person error(@Body Person person); } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi.java index 1fb1210..7335583 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi.java @@ -1,14 +1,17 @@ package com.github.lianjiatech.retrofit.spring.boot.test.http; +import java.util.List; +import java.util.concurrent.CompletableFuture; + import com.github.lianjiatech.retrofit.spring.boot.annotation.Intercept; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; -import com.github.lianjiatech.retrofit.spring.boot.retry.Retry; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; import com.github.lianjiatech.retrofit.spring.boot.test.ex.TestErrorDecoder; import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.Sign; import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.TimeStamp2Interceptor; import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.TimeStampInterceptor; + import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Body; @@ -16,9 +19,6 @@ import retrofit2.http.POST; import retrofit2.http.Query; -import java.util.List; -import java.util.concurrent.CompletableFuture; - /** * @author 陈添明 */ @@ -29,34 +29,34 @@ public interface HttpApi { /** - * Call
- * 不执行适配处理,直接返回Call对象 + * 其他任意Java类型
+ * 将响应体内容适配成一个对应的Java类型对象返回,如果http状态码不是2xx,直接抛错!
* * @param id id - * @return Call实例 + * @return 其他任意Java类型 */ @GET("person") - Call> getPersonCall(@Query("id") Long id); + Result getPerson(@Query("id") Long id); /** - * CompletableFuture
- * 将响应体内容适配成CompletableFuture对象返回 + * Void
+ * 不关注返回类型可以使用Void。如果http状态码不是2xx,直接抛错! * * @param id id - * @return CompletableFuture + * @return Void */ @GET("person") - CompletableFuture> getPersonCompletableFuture(@Query("id") Long id); + Void getPersonVoid(@Query("id") Long id); /** - * Void
- * 不关注返回类型可以使用Void。如果http状态码不是2xx,直接抛错! + * CompletableFuture
+ * 将响应体内容适配成CompletableFuture对象返回,异步调用 * * @param id id - * @return Void + * @return CompletableFuture */ @GET("person") - Void getPersonVoid(@Query("id") Long id); + CompletableFuture> getPersonCompletableFuture(@Query("id") Long id); /** * Response
@@ -69,54 +69,27 @@ public interface HttpApi { Response> getPersonResponse(@Query("id") Long id); /** - * 其他任意Java类型
- * 将响应体内容适配成一个对应的Java类型对象返回,如果http状态码不是2xx,直接抛错!
+ * Call
+ * 不执行适配处理,直接返回Call对象 * * @param id id - * @return 其他任意Java类型 + * @return Call实例 */ @GET("person") - Result getPerson(@Query("id") Long id); - + Call> getPersonCall(@Query("id") Long id); - /** - * . - * - * @param person . - * @return . - */ @POST("savePerson") Void savePersonVoid(@Body Person person); - - /** - * . - * - * @param person . - * @return . - */ @POST("savePerson") Result savePerson(@Body Person person); - /** - * . - * - * @param person . - * @return . - */ @POST("error") Person error(@Body Person person); - /** - * . - * - * @param personList . - * @return . - */ @POST("savePersonList") Result savePersonList(@Body List personList); - @POST("getString") String getString(@Body Person person); diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi2.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi2.java index bdcc5fb..f88afd7 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi2.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi2.java @@ -1,5 +1,7 @@ package com.github.lianjiatech.retrofit.spring.boot.test.http; +import java.util.Map; + import com.github.lianjiatech.retrofit.spring.boot.annotation.Intercept; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; @@ -7,13 +9,12 @@ import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.EnumIntercept; import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.EnvEnum; import com.github.lianjiatech.retrofit.spring.boot.test.interceptor.TimeStampInterceptor; + import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.HTTP; import retrofit2.http.Query; -import java.util.Map; - /** * @author 陈添明 */ @@ -22,22 +23,13 @@ @EnumIntercept(envEnum = EnvEnum.test) public interface HttpApi2 { - /** - * . - * - * @param id . - * @return . - */ @GET("person") Result getPerson(@Query("id") Long id); - @GET("testMap") Map> testMap(); - @HTTP(method = "get", path = "/getPersonBody", hasBody = true) Result getPersonBody(@Body Person person); - } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi3.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi3.java index bd6a4e4..703b72d 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi3.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/HttpApi3.java @@ -1,23 +1,23 @@ package com.github.lianjiatech.retrofit.spring.boot.test.http; +import java.util.concurrent.TimeUnit; + import com.github.lianjiatech.retrofit.spring.boot.annotation.OkHttpClientBuilder; import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; + import okhttp3.OkHttpClient; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; -import java.util.concurrent.TimeUnit; - /** * @author 陈添明 */ @RetrofitClient(baseUrl = "http://ke.com") public interface HttpApi3 { - @OkHttpClientBuilder static OkHttpClient.Builder okhttpClientBuilder() { return new OkHttpClient.Builder() @@ -27,13 +27,6 @@ static OkHttpClient.Builder okhttpClientBuilder() { } - /** - * . - * - * @param url . - * @param id . - * @return . - */ @GET Result getPerson(@Url String url, @Query("id") Long id); } diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/IllegalBaseUrlTestApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/IllegalBaseUrlTestApi.java index 6b187bd..790ae0b 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/IllegalBaseUrlTestApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/IllegalBaseUrlTestApi.java @@ -3,6 +3,7 @@ import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; + import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.jaxb.JaxbConverterFactory; import retrofit2.http.GET; @@ -11,7 +12,8 @@ /** * @author 陈添明 */ -@RetrofitClient(baseUrl = "${not.baseUrl}", converterFactories = {GsonConverterFactory.class, JaxbConverterFactory.class}) +@RetrofitClient(baseUrl = "${not.baseUrl}", + converterFactories = {GsonConverterFactory.class, JaxbConverterFactory.class}) public interface IllegalBaseUrlTestApi { @GET("person") diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/InterceptApi.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/InterceptApi.java index f21f3aa..1fc27e7 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/InterceptApi.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/http/InterceptApi.java @@ -3,12 +3,12 @@ import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Person; import com.github.lianjiatech.retrofit.spring.boot.test.entity.Result; + import retrofit2.http.GET; import retrofit2.http.Query; /** * @author 陈添明 - * @summary * @since 2022/1/21 4:19 下午 */ @RetrofitClient(baseUrl = "${test.baseUrl}") diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/CustomRetryInterceptor.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/CustomRetryInterceptor.java deleted file mode 100644 index 0a0b1ae..0000000 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/CustomRetryInterceptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.lianjiatech.retrofit.spring.boot.test.interceptor; - -import com.github.lianjiatech.retrofit.spring.boot.retry.BaseRetryInterceptor; -import com.github.lianjiatech.retrofit.spring.boot.retry.RetryRule; -import com.github.lianjiatech.retrofit.spring.boot.test.service.TestService; -import okhttp3.Response; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * @author 陈添明 - * @summary - * @since 2022/1/21 4:52 下午 - */ -@Component -public class CustomRetryInterceptor extends BaseRetryInterceptor { - - @Autowired - private TestService testService; - - @Override - protected Response retryIntercept(int maxRetries, int intervalMs, RetryRule[] retryRules, Chain chain) { - System.out.println("=============执行重试============="); - testService.test(); - try { - return chain.proceed(chain.request()); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/EnumIntercept.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/EnumIntercept.java index 953820d..60e5f8c 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/EnumIntercept.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/EnumIntercept.java @@ -1,11 +1,14 @@ package com.github.lianjiatech.retrofit.spring.boot.test.interceptor; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import com.github.lianjiatech.retrofit.spring.boot.annotation.InterceptMark; import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor; -import java.lang.annotation.*; - /** * 自动将注解上的参数值赋值到handleInterceptor实例上 * @@ -17,7 +20,6 @@ @InterceptMark public @interface EnumIntercept { - EnvEnum envEnum(); /** diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/Sign.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/Sign.java index 5fe80c0..7362e7f 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/Sign.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/interceptor/Sign.java @@ -1,11 +1,14 @@ package com.github.lianjiatech.retrofit.spring.boot.test.interceptor; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import com.github.lianjiatech.retrofit.spring.boot.annotation.InterceptMark; import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor; -import java.lang.annotation.*; - /** * 自动将注解上的参数值赋值到handleInterceptor实例上 * @@ -33,7 +36,6 @@ */ String accessKeySecret(); - /** * 拦截器匹配路径 * diff --git a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/service/TestService.java b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/service/TestService.java index 4c396dd..5072bf6 100644 --- a/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/service/TestService.java +++ b/src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/service/TestService.java @@ -4,13 +4,11 @@ /** * @author 陈添明 - * @summary * @since 2022/1/21 4:29 下午 */ @Service public class TestService { - public void test() { } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 6c6cb68..fda3b6a 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -24,10 +24,8 @@ retrofit: # 日志打印配置 log: - # 启用日志打印 - enable: true - # 日志打印拦截器 - logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor + # 启用全局日志打印 + enable-global-log: true # 全局日志打印级别 global-log-level: info # 全局日志打印策略 @@ -46,8 +44,6 @@ retrofit: global-retry-rules: - response_status_not_2xx - occur_io_exception - # 重试拦截器 - retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor # 熔断降级配置 degrade: diff --git a/src/test/resources/default-config.yml b/src/test/resources/default-config.yml index 2f436de..e7e4e58 100644 --- a/src/test/resources/default-config.yml +++ b/src/test/resources/default-config.yml @@ -8,10 +8,6 @@ retrofit: # 连接保活时间(秒) keep-alive-second: 300 - # 是否禁用void返回值类型 - disable-void-return-type: false - - # 全局转换器工厂 global-converter-factories: - com.github.lianjiatech.retrofit.spring.boot.core.BasicTypeConverterFactory @@ -24,15 +20,12 @@ retrofit: # 日志打印配置 log: # 启用日志打印 - enable: true - # 日志打印拦截器 - logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor + enable-global-log: true # 全局日志打印级别 global-log-level: info # 全局日志打印策略 global-log-strategy: basic - # 重试配置 retry: # 是否启用全局重试 @@ -45,8 +38,6 @@ retrofit: global-retry-rules: - response_status_not_2xx - occur_io_exception - # 重试拦截器 - retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor # 熔断降级配置 degrade: @@ -54,6 +45,7 @@ retrofit: enable: false # 熔断降级实现方式 degrade-type: sentinel + # 全局连接超时时间 global-connect-timeout-ms: 10000 # 全局读取超时时间 @@ -62,3 +54,5 @@ retrofit: global-write-timeout-ms: 10000 # 全局完整调用超时时间 global-call-timeout-ms: 0 + # 是否禁用void返回值类型 + disable-void-return-type: false