SpringCloud之服务熔断降级Hystrix
一 断路器
- 介绍
断路器类似于熔断保险丝,向调用方返回一个符合预期的可处理的备选响应Fallback,而不是长时间的等待或者抛出调用方无法处理的异常,类似于spring的异常通知。在provider提供者进行使用。 - 案例
(1)pom文件
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
(2)yaml配置文件
server:
port: 8001
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml #mybatis所在路径
type-aliases-package: com.atguigu.springcloud.entities #entity别名类
mapper-locations:
- classpath:mybatis/mapper/**/*.xml #mapper映射文件
spring:
application:
name: microservicecloud-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/cloudDB01
username: root
password: 123456
dbcp2:
min-idle: 5
initial-size: 5
max-total: 5
max-wait-millis: 200
eureka:
client: #客户端注册进eureka服务列表内
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: microservicecloud-dept8001-hystrix #自定义hystrix相关的服务名称信息
prefer-ip-address: true #访问路径可以显示IP地址
info:
app.name: atguigu-microservicecloud
company.name: www.atguigu.com
build.artifactId: $project.artifactId$
build.version: $project.version$
(3)主启动类
添加注解@EnableCircuitBreaker//对hystrixR熔断机制的支持
@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
@EnableDiscoveryClient //服务发现
@EnableCircuitBreaker//对hystrixR熔断机制的支持
public class DeptProvider8001_Hystrix_App{
public static void main(String[] args){
SpringApplication.run(DeptProvider8001_Hystrix_App.class, args);
}
}
(4)controller层的FallBack处理
在方法上添加 @HystrixCommand(fallbackMethod = “方法名”)进行容错处理
缺点:在每一个方法上添加fallback,类似于spring的异常通知,对于spring的aop而言会有强耦合性,还会出现方法同栈。
@RestController
public class DeptController
{
@Autowired
private DeptService service = null;
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
//一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
@HystrixCommand(fallbackMethod = "processHystrix_Get")
public Dept get(@PathVariable("id") Long id)
{
Dept dept = this.service.get(id);
if (null == dept) {
throw new RuntimeException("该ID:" + id + "没有没有对应的信息");
}
return dept;
}
public Dept processHystrix_Get(@PathVariable("id") Long id)
{
return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,null--@HystrixCommand")
.setDb_source("no this database in MySQL");
}
}
二 降级
- 介绍
服务降级就是整体资源不够了,忍痛把某些服务先关掉,待度过难关,在开启。该处理是在客户端实现完成的,与服务端无关。解决了上面提到的缺点,在实现了FallbackFactory接口的类中进行统一处理。 - 案例
(1)在消费者的公有api,在service接口新建实现了FallbackFactory接口的类,在需要进行熔断处理的方法中进行容错处理
@Component // 不要忘记添加,不要忘记添加
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
@Override
public DeptClientService create(Throwable throwable)
{
return new DeptClientService() {
@Override
public Dept get(long id)
{
return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭")
.setDb_source("no this database in MySQL");
}
@Override
public List<Dept> list()
{
return null;
}
@Override
public boolean add(Dept dept)
{
return false;
}
};
}
}
(2)修改microservicecloud-api工程,根据已经有的DeptClientService接口,新建一个实现了FallbackFactory接口的类DeptClientServiceFallbackFactory
添加fallbackFactory@FeignClient(value = “MICROSERVICECLOUD-DEPT”,fallbackFactory=DeptClientServiceFallbackFactory.class)
@FeignClient(value = "MICROSERVICECLOUD-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(Dept dept);
}
(3)在Feign服务的yaml配置文件中配置开启Hystirx
server:
port: 80
feign:
hystrix:
enabled: true
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
(4)模拟降级熔断,关闭提供者服务,再次进行访问,则会进行降级处理的内容
三 总结
- 服务熔断
一般是某个服务故障或异常引起,类似于保险丝,当某个异常条件被触发,直接熔断整个服务,而不是等到此服务超时,避免了服务雪崩效应。 - 服务降级
所谓降级,**一般从整体负荷考虑,当某个服务熔断后,服务器将不再被调用,此时客户端自己准备一个本地的FallBack回调,返回一个缺省值。**这样虽然服务水平下降,但服务不会宕机挂掉。
四 服务监控Dashboard
- pom文件
<!-- hystrix和 hystrix-dashboard相关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
</dependencies>
- yaml文件
server:
port: 9001
- 主启动类
条件注解@EnableHystrixDashboard
@SpringBootApplication
@EnableHystrixDashboard
public class DeptConsumer_DashBoard_App
{
public static void main(String[] args)
{
SpringApplication.run(DeptConsumer_DashBoard_App.class, args);
}
}
- 在需要监控的服务添加监控依赖
<!-- actuator监控信息完善 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
- 监控页面