---
title: "springCloud feign开启hystrix"
author: "shen84121062"
date: "2018-06-22T11:34:22Z"
tags: []
categories: ["互联网"]
slug: "springcloud-feign-hystrix"
draft: false
lastmod: "2018-06-22T11:34:22Z"
id: 2425398
url: "https://allen-shen.iteye.com/blog/2425398"
---

在做springcloud的feign整合的时候，学习到熔断机制，hystrix实现了熔断机制，而springcloud的feign默认整合了hystrix，所以添加feign依赖后就不用在添加hystrix，那么怎么才能让feign的熔断机制生效呢，官方称默认fegin的hystrix已经生效了只要按一下步骤做：

1.feign注解增加fallback属性

```
@FeignClient(name = "这里写服务名称"，fallback ="UserServiceAPIFallback .class")
public interface UserServiceAPI {
    @RequestMapping(method = RequestMethod.GET, value = "/user/getOne/{id}")
    User getOne(@PathVariable("id") Integer id);
}
```

 2.创建fallback类，注意fallback类要实现feignClient注解了的接口

```
/**
 * UserServiceClient服务器调用失败的退回类
 * @author gshen
 *
 */
@Component
public class UserServiceAPIFallback implements UserServiceAPI {
	@Override
	public User getOne(Integer id) {
		User user = new User();
		user.setId(-1);
		user.setUsername("默认用户");
		return user;
	}

}
```

 启动后，停掉userService的服务，显示找不到对应userService，这说明熔断没起作用

后来查阅官方资料发现，默认开启熔断更改为关闭熔断了，具体原因请看：[https://github.com/spring-cloud/spring-cloud-netflix/issues/1277](https://github.com/spring-cloud/spring-cloud-netflix/issues/1277)

官方提供开启开关

```
#开启feign熔断
feign:
  hystrix:
    enabled: true   
```

 启动服务发现返回结果成功

```
{
	"id": -1,
	"username": "默认用户",
	"password": null,
	"creater": null,
	"createTime": null,
	"updater": null,
	"updateTime": null,
	"salt": null,
	"nickname": null,
	"state": "1",
	"plainPassword": null,
	"roles": []
}
```