上编说了《RestTemplate+Ribbon整合断路器Hystrix》,这篇来看看如何Feign整合断路器Hystrix,Feign整合断路器Hystrix也是相对比较简单的。Feign默认已经自带断路器Hystrix,所以不需要像RestTemplate+Ribbon整合断路器Hystrix那样需要在SpringBoot的启动类添加注解。但是Feign自带断路器并没有打开,需要做些额外的配置。
feign:
hystrix:
enabled: true
1、 新建项目sc-eureka-client-consumer-feign-hystrix,对应的pom.xml文件如下
"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
spring-cloud
sc-eureka-client-consumer-feign
0.0.1-SNAPSHOT
jar
sc-eureka-client-consumer-feign
http://maven.apache.org
org.springframework.boot
spring-boot-starter-parent
2.0.4.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Finchley.RELEASE
pom
import
UTF-8
1.8
1.8
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-openfeign
备注:从继续关系可以看出spring-cloud-starter-openfeign已经集成断路器Hystrix
2、新建springboot启动类
package sc.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignApplication.class, args);
}
}
3、 新建配置文件bootstrap.yml和application.yml
bootstrap.yml
server:
port: 5800
application.yml
spring:
application:
name: sc-eureka-client-consumer-feign-hystrix
eureka:
client:
registerWithEureka: true #是否将自己注册到Eureka服务中,默认为true
fetchRegistry: true #是否从Eureka中获取注册信息,默认为true
serviceUrl:
defaultZone: http://localhost:5001/eureka/
feign:
hystrix:
enabled: true
说明:在application.yml配置文件添加了开启断路器Hystrix的配置项
4、新建服务消费者类UserService.java
package sc.consumer.service;
import java.util.Map;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import sc.consumer.model.User;
import sc.consumer.service.hystrix.UserServiceHystrix;
@FeignClient(value="sc-eureka-client-provider