1. pom依賴
依賴同feign一樣,不用修改,feign中默認包含了hystrix,側面說明hystrix是一個默認的組件,應該被開啓
<dependencies>
<dependency>
<groupId>com.honor</groupId>
<artifactId>interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
2. yml配置
啓用hystrix,設置feign.hystrix.enabled=true
server:
port: 9002
eureka:
client:
serviceUrl:
defaultZone: http://eureka-server-7001:7001/eureka/,http://eureka-server-7002:7002/eureka/,http://eureka-server-7003:7003/eureka/
# defaultZone: http://eureka-server-8001:8001/eureka/
instance:
instance-id: eureka-provider-9002 # 服務名稱
prefer-ip-address: true # 顯示ip地址
# 啓用斷路器
feign:
hystrix:
enabled: true
info: # 點擊註冊列表未服務出現的信息
app.name: springcloud
company.name: www.honor.com
build.artifactId: @project.artifactId@
build.version: @project.version@
spring:
application:
name: eureka-consumer-feign
3. 修改feign客戶端
feign的客戶端在interface公共模塊中
3.1 方式一:創建fallback類
這種方式相當於實現一個service接口類,會和服務提供者衝突,因爲服務提供者也會實現service接口,不建議使用
// fallback類
@Component
public class HelloServiceFallBack implements IHelloService {
public String sayHello(String name) {
return "hello " + name + ", current service is disable, place try it later.";
}
}
// 客戶端配置
@FeignClient(value = "eureka-provider", fallback = HelloServiceFallBack.class)
public interface IHelloService {
/**
* 打招呼
*
* @param name bb俠
* @return
*/
@GetMapping("/hello/{name}")
// @PathVariable必須包含名稱,不然無法啓動
String sayHello(@PathVariable("name") String name);
}
3.2 方式二:創建fallback工廠類
// fallback工廠
@Component
public class HelloServiceFallBackFactory implements FallbackFactory<IHelloService> {
public IHelloService create(Throwable throwable) {
return new IHelloService() {
public String sayHello(String name) {
return "hello " + name + ", current service is disable, place try it later.";
}
};
}
}
// 配置
@FeignClient(value = "eureka-provider", fallbackFactory = HelloServiceFallBackFactory.class)
public interface IHelloService {
/**
* 打招呼
*
* @param name bb俠
* @return
*/
@GetMapping("/hello/{name}")
// @PathVariable必須包含名稱,不然無法啓動
String sayHello(@PathVariable("name") String name);
}
4. 主啓動類
和feign一樣沒有變更
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaConsumerFeignHystrix9002Application {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerFeignHystrix9002Application.class, args);
}
}
5. 測試
當服務提供者8001、8002、8003都正常時跟平時調用一樣沒有區別,關閉8003模擬服務故障,你會發現當輪詢到8003時,會返回fallbackMethod指定方法中的內容,當重試多次以後沒有用,服務調用者就不會訪問8003了,等一段時間後,又會嘗試訪問8003,如果還是不行就又熔斷,如果訪問成功了,那就恢復正常。