代码信息
本篇文章涉及代码版本
组件 | 版本 |
---|---|
Spring Boot | 2.0.8.RELEASE |
Spring Cloud | Finchley.SR1 |
本篇文章涉及应用
应用 | 说明 |
---|---|
base-eureka | 服务发现 |
base-feign-hystrix | 声明式调用带降级 |
base-producer | 提供服务的最基础的应用 |
和zuul一样添加了hystrix依赖后,feign也实现了服务降级的操作。今天我们来实现feign + hystrix 实现feign的服务降级。
新建一个支持服务降级的Feign项目
构建maven依赖
添加feign和hystrix的依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
参数配置application.yml
这里需要注意一下和zuul你需要显式的打开feign.hystrix.enabled的支持才能使用服务降级
spring:
application:
name: base-feign-hystrix
server:
port: 8405
feign:
hystrix:
enabled: true
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka/
logging:
file: ${spring.application.name}.log
代码编写
主类
依次为springboot的注解,eureka注解,feign注解,hystrix的注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class FeignHystixApplication {
public static void main(String[] args) {
SpringApplication.run(FeignHystixApplication.class,args);
}
}
feign请求接口
在接口中我们指定HystrixClientFallback类为其服务降级类
@FeignClient(value = "base-producer",fallback = HystrixClientFallback.class)
public interface ClientService {
/**
* 测试的服务获取
* @return
*/
@RequestMapping(value = "getService",method = RequestMethod.POST)
String getService();
}
服务降级实现类
@Component
public class HystrixClientFallback implements ClientService {
/**
* 测试的服务获取
* @return
*/
@Override
public String getService() {
return "use hystrix fallback";
}
}
测试用的接口
@RestController
public class FeignController {
@Autowired
ClientService clientService;
@RequestMapping(value = "/consumer",method = RequestMethod.GET)
public String getClientService() {
return clientService.getService();
}
}
测试
现在我们依次启动base-eureka
、base-producer
、base-feign-hystrix
项目。
然后我们尝试访问测试地址http://localhost:8405/consumer
,返回内容
Services: [base-producer-upload, base-producer, base-zuul-upload, base-zuul-fallback, base-feign-hystrix]
然后我们关闭base-producer
项目,我们尝试再次访问测试地址。返回内容
use hystrix fallback
可以看到项目已经实现了服务降级。
补充:另外一种方式实现服务降级
本来想再分一篇,但是想想一个简单的服务降级没必要写来写去的,所以直接补充道后面了。
feign调用接口
此时指定的fallbackFactory而不是fallback
@FeignClient(value = "base-producer",fallbackFactory = HystrixClientFactory.class)
public interface ClientService {
/**
* 测试的服务获取
* @return
*/
@RequestMapping(value = "getService",method = RequestMethod.POST)
String getService();
}
服务降级实现类
@Component
public class HystrixClientFactory implements FallbackFactory<ClientService> {
@Override
public ClientService create(Throwable throwable) {
return new ClientService() {
@Override
public String getService() {
return "use factory fallback";
}
};
}
}
具体测试结果也是可以实现服务降级。
本篇文章并未贴出所有代码,涉及的源码下载地址:https://gitee.com/daifylearn/cloud-learn
ps.上述的所有项目都是可以成功运行的。但是在后期为了实现每个应用端口尽量不冲突会有些许调整,而后续某次作死调整结构和名称可能会导致部分项目无法运行o(╯□╰)o,如果发现请留言我进行修改。