Feign包含了Ribbon和Hystrix,這個在實戰中才慢慢體會到它的意義,所謂的包含並非Feign的jar包包含有Ribbon和Hystrix的jar包這種物理上的包含,而是Feign的功能包含了其餘二者的功能這種邏輯上的包含。簡言之:Feign能幹Ribbon和Hystrix的事情,可是要用Ribbon和Hystrix自帶的註解必需要引入相應的jar包才能夠。web
1.引入依賴spring
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->app
<dependency>maven
<groupId>org.springframework.cloud</groupId>ide
<artifactId>spring-cloud-starter-feign</artifactId>spring-boot
<version>1.4.6.RELEASE</version>url
</dependency>.net
2.配置文件中開啓服務code
feign.hystrix.enabled=trueserver
3.啓動類註解開啓
@EnableFeignClients
public class DemoFeignApplication {
public static void main(String[] args) {
SpringApplication.run(DemoFeignApplication.class, args);
}
}
4.feign 是基於接口的註解方式實現的新建一個接口
@FeignClient(value = "two-client",fallback = SchedualServiceHiHystric.class)
public interface UserService {
@RequestMapping("/home/indexd")
String getIndex();
}
FeignClient("two-client"")註解裏eureka-client指的是提供服務的服務名
fallback 自定義異常類
5.異常類的實現
public class SchedualServiceHiHystric implements UserService {
public String getIndex() {
return "服務沒有開啓";
}
}
6.請求controller
@Autowired
private UserService userService;
@RequestMapping("/index")
public String index(){
logger.info("index方法");
return userService.getIndex();
}
7.結果,當調用的服務端沒有開啓的時候
註釋:1.maven的依賴必定要匹配,否則版本不匹配就會報不少沒法預知的異常(本人遇到很坑)
2.配置貼出來供參考
<dependencies>
<!--EuekaClient客戶端依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.3.6.RELEASE</version>
</dependency>
<!--Web端依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.3.6.RELEASE</version>
</dependency>
</dependencies>
#server.port=8013 #eureka.client.service-url.defaultZone=http://localhost:8000/eureka/ #spring.application.name=three-client #feign.hystrix.enabled=true server: port: 8013 eureka: client: service-url: defaultZone: http://localhost:8000/eureka/ spring: application: name: three-client feign: hystrix: enabled: true hystrix: threadpool: default: coreSize: 500 #缺省爲10 stream: maxConcurrentConnections: 20 bus: enabled: true command: default: execution: timeout: enabled: false isolation: thread: timeoutInMilliseconds: 60000 ribbon: eureka: enabled: true