一 前言
前文Feign配置一中講述了feign的工作流程,日志設置,基本的HTTP遠程過程調用,以及相關的注解說明;這篇文章主要說明的是feign的相關支持配置,以及替換原生的FeignClient;
二 OkHttp
目前主流的是使用OkHttp替換原生的FeignClient,Apache的HttpClient感覺沒有OkHttp好,所以就不提了。
OkHttp 詳細的信息可以參照文檔 https://square.github.io/okhttp/; 主要特色如下:
- HTTP2支持多請求一台主機共享socket;
- 連接池減少請求延遲
- GZIP壓縮,減少傳輸體積
- 支持響應緩存,減少重復響應;
2.1 引入依賴
父工程中已經引入springboot start依賴,這邊不會重復引入;在原來工程的基礎上新增 feign-okhttp
依賴;
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
</dependencies>
2.2 application.yml
跟配置一文章中不同之處是不用默認的feign配置,替換為開啟okhttp配置;
server:
port: 8093
spring:
application:
name: feign-client # 應用名稱
eureka:
client:
service-url:
# 服務注冊地址
defaultZone: http://peer1:10081/eureka/,http://peer2:10082/eureka/,http://peer3:10083/eureka/
logging:
level:
com.zszxz.feign.service: Debug
# 開啟okhttp
feign:
okhttp:
enabled: true
2.3 FeignOkHttpConfig
配置中都是基本配置,設置讀取時間,超時時間,連接池,額外配置(例如攔截器)讀者可以參照上面文檔研究;
/**
* @Author lsc
* <p> okhttp基本配置 </p>
*/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignOkHttpConfig {
@Bean
public okhttp3.OkHttpClient okHttpClient(){
return new okhttp3.OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool())
.build();
}
}
2.5 service
這邊調用的之前eureka-client提供的一個表現層API,跟平常的API沒有什么區別;如果不懂可可以看看之前的文章或者拉取下源碼
/**
* @Author lsc
* <p> </p>
*/
@FeignClient( name = "eureka-client", value = "eureka-client")
public interface FeignService {
@GetMapping("zszxz/feign")
public String getFeign();
}
2.6 controller
controller層不變,直接調用service層API
/**
* @Author lsc
* <p> feign 表現層 </p>
*/
@RestController
public class FeignController {
@Autowired
FeignService feignService;
@GetMapping("zszxz/feign")
public String getFeign(){
// 調用 getFeign方法
return feignService.getFeign();
}
}
2.7 訪問結果
三 Feign集成配置說明
3.1 默認集成ribbon
feign默認集成了ribbon,不想像上面的配置文件中全局配置超時時間,而是單獨配置ribbon可以參照如下:
#ribbon的超時時間
ribbon:
# 讀超時時間
ReadTimeout: 60000
# 連接的超時時間
ConnectTimeout: 30000
3.2 開啟 hystrix
默認情況下feign是沒有開啟hystrix,需要手動開啟;
feign:
# 開啟okhttp
okhttp:
enabled: true
# 開啟 hystrix
hystrix:
enabled: true
# 熔斷機制
hystrix:
shareSecurityContext: true
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 10000
circuitBreaker:
sleepWindowInMilliseconds: 50000
forceClosed: true
四 其他配置說明
經過這兩篇文章學習,基本的feign操作已經很全面,如官網上說的feign的繼承,知識追尋者覺得是沒必要學習,耦合度太高了;GZIP壓縮,okhttp是支持的,跟平常調用沒什么區別,如果要手動配置也就是返回值是byte而已,所以讀者了解以下即可;還有一個回調處理,官網上的示例也很明了,讀者很容易上手,如果時間充裕有可能會在hystrix講解;