Hystrix断路器
为什么需要 Hystrix断路器(雪崩现象)
在理想状态下,一个应用依赖的服务都是健康可用的,我们可以正常的处理所有的请求。
当某一个服务出现延迟时,所有的请求都阻塞在依赖的服务Dependency I .
当依赖I 阻塞时,大多数服务器的线程池就出现阻塞(BLOCK),影响整个线上服务的稳定性
在复杂的分布式架构的应用程序有很多的依赖,都会不可避免地在某些时候失败。高并发的依赖失败时如果没有隔离措施,当前应用服务就有被拖垮的风险
解决方案
对依赖做隔离,Hystrix就是处理依赖隔离的框架,同时也是可以帮我们做依赖服务的治理和监控.。当我们使用了Hystrix时,Hystrix将所有的外部调用都封装成一个HystrixCommand或者HystrixObservableCommand对象,这些外部调用将会在一个独立的线程中运行。我们可以将出现问题的服务通过熔断、降级等手段隔离开来,这样不影响整个系统的主业务
Hystrix
Hystrix是保证微服务群健壮框架,做了隔离,熔断,降级等操作.最终达到不会由于某一个服务出问题而导致雪崩现象,让整体群死掉.
Hystrix 通过如下机制来解决雪崩效应问题:
① 资源隔离(限流):包括线程池隔离和信号量隔离,限制调用分布式服务的资源使用,某一个调用的服务出现问题不会影响其他服务调用。
② 融断:当失败率达到阀值自动触发降级(如因网络故障/超时造成的失败率高),熔断器触发的快速失败会进行快速恢复。
③ 降级机制:超时降级、资源不足时(线程或信号量)降级,降级后可以配合降级接口返回托底数据。
④ 缓存:提供了请求缓存、请求合并实现。
Hystrix实现(服务提供者实现)
ribbon实现
1.创建服务提供者模块
2.导jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
3.在启动类中添加注解@EnableHystrix
@SpringBootApplication
@EnableEurekaClient //定义服务端
@EnableHystrix //开启Hystrix
public class UserProviderApplication_hystri8002 {
public static void main(String[] args) {
SpringApplication.run(UserProviderApplication_hystri8002.class,args);
}
}
4.代码实现
@RestController
@RequestMapping("/provider")
public class UserController {
@RequestMapping("/user/{id}")
@HystrixCommand(fallbackMethod = "failGet") //出现错误调用dailGet方法
public User getUser(@PathVariable("id") Long id){
if(id == 2){
throw new RuntimeException("报错啦");
}
return new User(id,"zs_provider222");
}
public User failGet(Long id){
return new User(id,"用户不存在");
}
}
5.测试
Feign实现
为什么使用
问题:
每个方法都要加回调并且耦合高
解决方案:
可以使用spring面向切面编程,为feign的接口创建一个代理对象,完成对服务调用,当发现熔断后就调用同名托底方法
实现(feign服务消费者实现)
1.创建接口UserClient类
@FeignClient(value = "USER-PROVIDER",fallback = UserClientFall.class)
public interface UserCilent{
@RequestMapping("/provider/user/{id}")
public User getUser(@PathVariable("id") Long id);
}
2.接口实现类
@Component
public class UserClientFall implements UserCilent {
@Override
public User getUser(Long id) {
return new User(id,"用户不存在");
}
}
3.yml配置
server:
port: 9001
eureka:
client:
registerWithEureka: false #不注册到Eureka,不在注册中心显示
service-url:
defaultZone: http://eureka-7001.com:7001/eureka,http://eureka-7002.com:7002/eureka
feign:
hystrix:
enabled: true #开启熔断支持
client:
config:
remote-service: #服务名,填写default为所有服务
connectTimeout: 3000
readTimeout: 3000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
4.启动类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = "cn.itsource.springcloud.fegin")
public class UserConsumerAppliction_9003 {
public static void main(String[] args) {
SpringApplication.run(UserConsumerAppliction_9003.class,args);
}
}