4Hystrix Feign · SpringCloud微服务实战 · 看云
4. Hystrix Feign
导航
前面我们详细介绍了Hystrix与Ribbon的使用,下面我们来详细说明Hystrix与Feign的使用,Feign本身已经对Hystrix提供了支持,使用时只要打开开关就行了。下面我们新建一个项目演示。
本节代码地址
GitHub: https://github.com/xuyisu/fw-sping-cloud/tree/master/fw-cloud-hystrix/fw-cloud-hystrix-feign
GitHub: https://github.com/xuyisu/fw-sping-cloud/tree/master/fw-cloud-client/fw-cloud-client-eureka
4.1 新建项目
4.2 maven 配置
需要将feign的依赖加入进来
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
4.3 新建启动类
需要加上@EnableHystrix和@EnableFeignClients的注解
@EnableFeignClients
@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class FwHystrixFeignApplication {
public static void main(String[] args) {
SpringApplication.run(FwHystrixFeignApplication.class, args);
}
}
4.4 应用配置
最主要的是feign.hystrix.enabled: true需要打开,否则Hystrix 不起作用,默认是关闭的。
server:
port: 8676
spring:
application:
name: fw-hystrix-feign
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
feign:
hystrix:
enabled: true #开启hystrix
4.5 新建调用的service
@FeignClient注解的使用和普通的Feign 客户端没什么区别,主要就是加了一个fallback的类,回退的方法需要实现当前service的接口。
@FeignClient(value = "fw-register-eureka-client", fallback = EurekaFeignServiceFailure.class)
public interface EurekaFeignService {
@GetMapping("/hello")
String hello();
}
4.6 新建回退类
@Service
public class EurekaFeignServiceFailure implements EurekaFeignService {
@Override
public String hello() {
return "网络异常,稍后再试,请拿好手牌";
}
}
4.7 新建控制层
用于接收请求
@RestController
@Slf4j
public class EurekaFeignController {
@Resource
private EurekaFeignService eurekaFeignService;
@GetMapping("/feignInfo")
public String feignInfo() {
String message = eurekaFeignService.hello();
log.info(message);
return message;
}
}
4.8 启动项目
这里需要先启动Eureka,再起动fw-cloud-client-eureka项目,然后在启动当前项目
如果当前项目先启动报错
Caused by: java.lang.ClassNotFoundException: com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect
在maven里面添加这个依赖就可以了
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
启动好的想过应该是这样的
下面利用Postman测试
4.9 对Hystrix配置
指定接口方法的配置就是默认的CommandKey,@FeignClient注解上的名称是默认的GroupKey,具体很多配置,可以自己尝试一下
hystrix:
command:
EurekaFeignService#hello(): #指定接口方法的超时规则
execution:
isolation:
thread:
timeoutInMilliseconds: 500 #超时时间
circuitBreaker:
requestVolumeThreshold: 3 #请求并发数
#全局的
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500 #超时时间
circuitBreaker:
requestVolumeThreshold: 3 #请求并发数

