Skip to content

Commit

Permalink
support simple timeout config
Browse files Browse the repository at this point in the history
  • Loading branch information
chentianming11 committed Oct 7, 2022
1 parent b2fc02f commit 049c3b3
Show file tree
Hide file tree
Showing 14 changed files with 272 additions and 37 deletions.
31 changes: 19 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ gitee项目地址:[https://gitee.com/lianjiatech/retrofit-spring-boot-starter]
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.3.7</version>
<version>2.3.8</version>
</dependency>
```

Expand Down Expand Up @@ -143,6 +143,17 @@ retrofit:
- response_status_not_2xx
- occur_io_exception

# 全局超时时间配置
global-timeout:
# 全局读取超时时间
read-timeout-ms: 10000
# 全局写入超时时间
write-timeout-ms: 10000
# 全局连接超时时间
connect-timeout-ms: 10000
# 全局完整调用超时时间
call-timeout-ms: 0

# 熔断降级配置
degrade:
# 熔断降级类型。默认none,表示不启用熔断降级
Expand All @@ -168,8 +179,15 @@ retrofit:
## 高级功能
### 超时时间配置
如果仅仅需要修改`OkHttpClient`的超时时间,可以通过`@RetrofitClient`相关字段修改,或者全局超时配置修改。


### 自定义OkHttpClient

If you need to modify other configuration of `OkHttpClient`, you can do it by customizing `OkHttpClient`, the steps are as follows:

1. 实现`SourceOkHttpClientRegistrar`接口,调用`SourceOkHttpClientRegistry#register()`方法注册`OkHttpClient`。

```java
Expand All @@ -180,17 +198,6 @@ retrofit:
@Override
public void register(SourceOkHttpClientRegistry registry) {
// 替换默认的SourceOkHttpClient,可以用来修改全局OkhttpClient设置
registry.register(Constants.DEFAULT_SOURCE_OK_HTTP_CLIENT, new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(5))
.writeTimeout(Duration.ofSeconds(5))
.readTimeout(Duration.ofSeconds(5))
.addInterceptor(chain -> {
log.info("============replace default SourceOkHttpClient=============");
return chain.proceed(chain.request());
})
.build());
// 添加testSourceOkHttpClient
registry.register("testSourceOkHttpClient", new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(3))
Expand Down
11 changes: 10 additions & 1 deletion README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.3.7</version>
<version>2.3.8</version>
</dependency>
```

Expand Down Expand Up @@ -118,6 +118,11 @@ retrofit:
- response_status_not_2xx
- occur_io_exception

global-timeout:
read-timeout-ms: 10000
write-timeout-ms: 10000
connect-timeout-ms: 10000
call-timeout-ms: 0
degrade:
degrade-type: none
global-sentinel-degrade:
Expand All @@ -136,6 +141,10 @@ retrofit:
## Advanced Features
### Timeout config
If you only need to modify the timeout time of `OkHttpClient`, you can modify it through the relevant fields of `@RetrofitClient`, or modify the global timeout configuration.

### Customize OkHttpClient

1. Implement the `SourceOkHttpClientRegistrar` interface and call the `SourceOkHttpClientRegistry#register()` method to register the `OkHttpClient`.
Expand Down
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.3.7</version>
<version>2.3.8</version>

<name>retrofit-spring-boot-starter</name>
<description>retrofit-spring-boot-starter</description>
Expand Down Expand Up @@ -41,7 +41,7 @@
<junit.version>4.13.1</junit.version>
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
<slf4j-api.version>1.7.25</slf4j-api.version>
<spring-boot.version>2.0.9.RELEASE</spring-boot.version>
<spring-boot.version>2.2.11.RELEASE</spring-boot.version>
<okhttp.version>3.14.9</okhttp.version>
<sentinel.version>1.6.3</sentinel.version>
<jackson.version>2.12.6.1</jackson.version>
Expand All @@ -58,7 +58,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
<version>2.0.4.RELEASE</version>
<version>2.2.9.RELEASE</version>
<scope>provided</scope>
<exclusions>
<exclusion>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.lianjiatech.retrofit.spring.boot.config;

import lombok.Data;

/**
* 只有在@RetrofitClient.sourceOkHttpClient为NO_SOURCE_OK_HTTP_CLIENT时才有效
* @author 陈添明
* @since 2022/10/7 4:23 下午
*/
@Data
public class GlobalTimeoutProperty {

/**
* 全局连接超时时间
*/
private int connectTimeoutMs = 10_000;

/**
* 全局读取超时时间
*/
private int readTimeoutMs = 10_000;

/**
* 全局写入超时时间
*/
private int writeTimeoutMs = 10_000;

/**
* 全局完整调用超时时间
*/
private int callTimeoutMs = 0;
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public class RetrofitProperties {
@NestedConfigurationProperty
private GlobalLogProperty globalLog = new GlobalLogProperty();

/**
* 全局超时配置
*/
@NestedConfigurationProperty
private GlobalTimeoutProperty globalTimeout = new GlobalTimeoutProperty();

/**
* 全局转换器工厂,转换器实例优先从Spring容器获取,如果没有获取到,则反射创建。
* global converter factories, The converter instance is first obtained from the Spring container. If it is not obtained, it is created by reflection.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public interface Constants {

String STR_EMPTY = "";

String DEFAULT_SOURCE_OK_HTTP_CLIENT = "defaultSourceOkHttpClient";
String NO_SOURCE_OK_HTTP_CLIENT = "";

String SPH_U_CLASS_NAME = "com.alibaba.csp.sentinel.SphU";

Expand All @@ -19,4 +19,6 @@ public interface Constants {
String RETROFIT = "retrofit";

String DEFAULT_CIRCUIT_BREAKER_CONFIG = "defaultCircuitBreakerConfig";

int INVALID_TIMEOUT_VALUE = -1;
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,42 @@
/**
* 原始OkHttpClient,根据该名称到#{@link SourceOkHttpClientRegistry}查找对应的OkHttpClient来构建当前接口的OkhttpClient。
*/
String sourceOkHttpClient() default Constants.DEFAULT_SOURCE_OK_HTTP_CLIENT;
String sourceOkHttpClient() default Constants.NO_SOURCE_OK_HTTP_CLIENT;


/*===============以下属性只有在sourceOkHttpClient为NO_SOURCE_OK_HTTP_CLIENT时才有效=================*/

/**
* Sets the default connect timeout for new connections. A value of 0 means no timeout,
* otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.
* If it is configured as -1, the global default configuration is used.
*
*/
int connectTimeoutMs() default Constants.INVALID_TIMEOUT_VALUE;

/**
* Sets the default read timeout for new connections. A value of 0 means no timeout,
* otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.
* If it is configured as -1, the global default configuration is used.
*
*/
int readTimeoutMs() default Constants.INVALID_TIMEOUT_VALUE;

/**
* Sets the default write timeout for new connections. A value of 0 means no timeout,
* otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.
* If it is configured as -1, the global default configuration is used.
*
*/
int writeTimeoutMs() default Constants.INVALID_TIMEOUT_VALUE;


/**
* Sets the default timeout for complete calls. A value of 0 means no timeout,
* otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.
* If it is configured as -1, the global default configuration is used.
*
*/
int callTimeoutMs() default Constants.INVALID_TIMEOUT_VALUE;

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.github.lianjiatech.retrofit.spring.boot.config.GlobalTimeoutProperty;
import com.github.lianjiatech.retrofit.spring.boot.config.RetrofitProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
Expand Down Expand Up @@ -90,9 +93,32 @@ public boolean isSingleton() {
private OkHttpClient createOkHttpClient() {
RetrofitClient retrofitClient =
AnnotatedElementUtils.findMergedAnnotation(retrofitInterface, RetrofitClient.class);
OkHttpClient sourceOkHttpClient = retrofitConfigBean.getSourceOkHttpClientRegistry()
.get(Objects.requireNonNull(retrofitClient).sourceOkHttpClient());
OkHttpClient.Builder okHttpClientBuilder = sourceOkHttpClient.newBuilder();

OkHttpClient.Builder okHttpClientBuilder;
if (Constants.NO_SOURCE_OK_HTTP_CLIENT.equals(Objects.requireNonNull(retrofitClient).sourceOkHttpClient())) {
// 使用默认超时时间创建OkHttpClient
GlobalTimeoutProperty globalTimeout = retrofitConfigBean.getRetrofitProperties().getGlobalTimeout();

int connectTimeoutMs = retrofitClient.connectTimeoutMs() == Constants.INVALID_TIMEOUT_VALUE
? globalTimeout.getConnectTimeoutMs() : retrofitClient.connectTimeoutMs();
int readTimeoutMs = retrofitClient.readTimeoutMs() == Constants.INVALID_TIMEOUT_VALUE
? globalTimeout.getReadTimeoutMs() : retrofitClient.readTimeoutMs();
int writeTimeoutMs = retrofitClient.writeTimeoutMs() == Constants.INVALID_TIMEOUT_VALUE
? globalTimeout.getWriteTimeoutMs() : retrofitClient.writeTimeoutMs();
int callTimeoutMs = retrofitClient.callTimeoutMs() == Constants.INVALID_TIMEOUT_VALUE
? globalTimeout.getCallTimeoutMs() : retrofitClient.callTimeoutMs();

okHttpClientBuilder = new OkHttpClient.Builder()
.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS)
.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeoutMs, TimeUnit.MILLISECONDS)
.callTimeout(callTimeoutMs, TimeUnit.MILLISECONDS);
} else {
OkHttpClient sourceOkHttpClient = retrofitConfigBean.getSourceOkHttpClientRegistry()
.get(retrofitClient.sourceOkHttpClient());
okHttpClientBuilder = sourceOkHttpClient.newBuilder();
}

if (isEnableDegrade(retrofitInterface)) {
okHttpClientBuilder.addInterceptor(retrofitConfigBean.getRetrofitDegrade());
}
Expand Down Expand Up @@ -159,7 +185,8 @@ private List<Interceptor> findInterceptorByAnnotation() {
private Retrofit createRetrofit() {
RetrofitClient retrofitClient =
AnnotatedElementUtils.findMergedAnnotation(retrofitInterface, RetrofitClient.class);
String baseUrl = RetrofitUtils.convertBaseUrl(retrofitClient, retrofitClient.baseUrl(), environment);
String baseUrl = RetrofitUtils.convertBaseUrl(retrofitClient, Objects.requireNonNull(retrofitClient).baseUrl(),
environment);

OkHttpClient client = createOkHttpClient();
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
Expand All @@ -186,7 +213,7 @@ private Retrofit createRetrofit() {
converterFactories.addAll(Arrays.asList(retrofitClient.converterFactories()));
converterFactories.addAll(Arrays.asList(retrofitConfigBean.getGlobalConverterFactoryClasses()));
converterFactories.forEach(converterFactoryClass -> retrofitBuilder
.addConverterFactory(AppContextUtils.getBeanOrNew(applicationContext, converterFactoryClass)));
.addConverterFactory(AppContextUtils.getBeanOrNew(applicationContext, converterFactoryClass)));

return retrofitBuilder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ public class SourceOkHttpClientRegistry {

public SourceOkHttpClientRegistry(List<SourceOkHttpClientRegistrar> registrars) {
this.registrars = registrars;
this.okHttpClientMap = new HashMap<>(8);
this.okHttpClientMap.put(Constants.DEFAULT_SOURCE_OK_HTTP_CLIENT, new OkHttpClient());
this.okHttpClientMap = new HashMap<>(4);
}

@PostConstruct
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,7 @@ public class CustomSourceOkHttpClientRegistrar implements SourceOkHttpClientRegi
@Override
public void register(SourceOkHttpClientRegistry registry) {

// 替换默认的SourceOkHttpClient,可以用来修改全局OkhttpClient设置
registry.register(Constants.DEFAULT_SOURCE_OK_HTTP_CLIENT, new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(5))
.writeTimeout(Duration.ofSeconds(5))
.readTimeout(Duration.ofSeconds(5))
.addInterceptor(chain -> {
log.info("============replace default SourceOkHttpClient=============");
return chain.proceed(chain.request());
})
.build());

// 添加testSourceOkHttpClient
// 注册testSourceOkHttpClient
registry.register("testSourceOkHttpClient", new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(3))
.writeTimeout(Duration.ofSeconds(3))
Expand Down
Loading

0 comments on commit 049c3b3

Please sign in to comment.