您的位置:首页 > 编程语言 > Java开发

【Spring Cloud】Hystrix 防御机制

2017-11-26 14:08 459 查看
本节大纲:

- 简介

- 架构图

- 创建项目(接着上一章节)

- 在Fcat实战项目中的应用

简介

Hystrix的职责是:在一个分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败。

Hystrix提供了熔断、隔离、Fallback、cache、监控等功能,能够在一个、或多个依赖同时出现问题时保证系统依然可用;

断路器可以防止一个应用程序多次试图执行一个操作,即很可能失败,允许它继续而不等待故障恢复或者浪费 CPU 周期,而它确定该故障是持久的。

服务雪崩效应

在微服务架构中通常会有多个服务层调用,基础服务的故障可能会导致级联故障,进而造成整个系统不可用的情况;

特点

断路器机制

避免发送大量无效请求影响系统吞吐量, 并且断路器有自我检测并恢复的能力

Fallback

对于查询操作, 我们可以实现一个fallback方法, 当请求后端服务出现异常的时候, 可以使用fallback方法返回的值. fallback方法的返回值一般是设置的默认值或者来自缓存.

资源隔离

通过线程池来实现资源隔离,不同的服务放入不同的线程池。

架构图



创建项目

关键代码

在网关项目中的appliation.yml文件中开启Hystrix

feign:
hystrix:
enabled: true


创建Feign客户端调用失败的实现类UserFeignImpl

import com.xfdmao.gate.feign.UserFeign;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

@Component
public class UserFeignImpl implements UserFeign{
@Override
public String getHome() {
return "hystrix getHome";
}

@Override
public String sayHi(@RequestParam(value = "username") String username) {
return "hystrix sayHi";
}
}


在UserFeign接口定义Hystrix的fallback实现类

import com.xfdmao.gate.feign.impl.UserFeignImpl;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value="fcat-user", fallback = UserFeignImpl.class)
public interface UserFeign {

@RequestMapping(value = "/",method = RequestMethod.GET)
String getHome();

@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHi(@RequestParam(value = "username") String username);
}


启动访问

依次启动:CenterApplication、UserApplication、GateApplication

访问测试:http://localhost:8762/userFeign/hi

在Fcat项目中的应用



源码地址:https://gitee.com/xfdm_admin/spring-cloud/tree/master

更多相关内容请查看:

angular、spring cloud 开源实战项目源码:https://gitee.com/xfdm/FCat

QQ群:549141844

代码持续更新…
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring-cloud