feign中對ribbon的配置
主要是在ribbon-core.jar文件下,com.netflix.client.config包下,其中DefaultClientConfigImpl類為默認配置
配置客戶端和負載均衡器的最簡單方法是符合特定格式的屬性:
<clientName>.<namespace>.< propertyName > = <value>
可以在類路徑或作為系統屬性的文件中定義屬性
默認情況下,“ribbon”應該是namespace。
如果沒有為指定的客戶端指定屬性,com.netflix.client.ClientFactory仍然會為所有必需的屬性創建客戶端和負載均衡器。默認值在這個類中指定為常量。
如果一個屬性丟失了clientName,那么它將被解釋為一個適用於所有客戶端的屬性。例如
ribbon.ReadTimeout = 1000
這將為所有客戶端建立默認的ReadTimeout屬性。
您還可以通過構造DefaultClientConfigImpl的實例來編程設置屬性。
如果希望在不同的名稱空間中定義屬性,例如“foo”
myclient.foo.ReadTimeout = 1000
feign中對hystrix的配置
在對hystrix進行配置之前首先要確認feign.hystrix.enabled參數設置為true(開起Hystrix熔斷器保護),否則參數設置會關閉Feign客戶端的hystrix,其主要的配置是對HystrixCommand的配置,是在hystrix-core.jar文件下com.netflix.hystrix.HystrixCommandProperties類中,如下截圖為某些參數配置
如配置全局的超時時間:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000//默認為1000ms即1s
服務調用者
改造服務調用者
controller
/**線程睡眠主要演示ribbon的服務重試機制,當超過消費者配置的連接超時時,進行第二次重連 * 不接收參數 * @return * @throws InterruptedException */ @SuppressWarnings("deprecation") @RequestMapping(value = "/hello1", method = RequestMethod.GET) public String hello() throws InterruptedException { ServiceInstance instance = client.getLocalServiceInstance(); logger.info("/hello1,host:{},service_id:{}",instance.getHost(),instance.getServiceId()); //測試超時 int sleep = new Random().nextInt(3000); logger.info("sleep time:{}",sleep); Thread.sleep(sleep); return "hello spring cloud"; }
啟動類服務消費者
package com.niugang; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; /** * feign版消費者 * * @author niugang * */ @SpringBootApplication @EnableDiscoveryClient //掃描聲明它們是feign客戶端的接口(通過@FeignClient) @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
配置
調用服務接口
服務降級類
controller
測試
啟動注冊中心,啟動服務類,啟動消費者
從控制台打印的日志可以看書,但線程睡眠超過2000ms時,消費者會常識第二次重連。
當停掉服務提供者:
輸入:http://localhost:9001/feign-consumer
執行相應的服務降級函數
輸入:http://localhost:9001/feign-consumer1/zhangsan
執行相應的服務降級函數
微信公眾號





