什么是Hystris(作用?):
在分布式系统中,每个服务都可能会调用很多其他服务,被调用的那些服务就是依赖服务,有的时候某些依赖服务出现故障也是很常见的。
Hystrix 可以让我们在分布式系统中对服务间的调用进行控制,加入一些调用延迟或者依赖故障的容错机制。Hystrix 通过将依赖服务进行资源隔离,进而阻止某个依赖服务出现故障时在整个系统所有的依赖服务调用中进行蔓延;同时Hystrix 还提供故障时的 fallback 降级机制。
总而言之,Hystrix 通过这些方法帮助我们提升分布式系统的可用性和稳定性。
1.熔断机制是对应雪崩效应的一种微服务链路保护机制。
当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回”错误”的响应信息。当检测到该节点微服务响应正常后恢复调用链路,在SpringCloud框架机制通过Hystrix实现,Hystrix会监控微服务见调用的状况,当失败的调用到一个阈值,缺省是5秒内20次调用失败就会启动熔断机制,熔断机制的注解是**@HystrixCommand**
(1.导入依赖:)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
(2.编写配置文件:application.yml)
server:
port: 8001
# mybatis配置
mybatis:
type-aliases-package: com.fang.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
# spring配置
spring:
application:
name: springcloud-provider-depts
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
#Eureka的配置,服务注册到哪里
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-provider-dept-hystrix-8001 #修改eureka上的默认描述信息!
#info装置
info:
app.name: fang.springcloud
company.name: blog.fangstudy.com
(3.实现并且开启这个功能: )
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "getHystrix")//指定要熔断的一个解决方案
public Dept get(@PathVariable("id") Long id){
Dept dept=deptService.queryById(id);
if(dept==null){
throw new RuntimeException("id=>"+id+",不存在该用户,或者信息无法找到。。。");
}
return dept;
}
//备选方案(hystrix)
public Dept getHystrix(@PathVariable("id") Long id){
Dept dept=new Dept();
dept.setDeptno(id);
dept.setDname("id=>\"+id+\",不存在该用户,或者信息无法找到。。。(hystrix)");
dept.setSource("no database");
return dept;
}
}
(4.配置类:)
ps:在启动类中记得加 @EnableCircuitBreaker//添加对熔断的支持
然后开启服务进行测试即可…