服务熔断
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "hystrixGet")
public Dept get(@PathVariable("id") Long id) {
Dept dept = deptService.queryById(id);
if (dept==null) {
throw new RuntimeException("id+=>" + id + "不存在该用户,或者信息无法找到");
}
return dept;
}
//备用方法
public Dept hystrixGet(@PathVariable("id") Long id) {
return new Dept()
.setDeptno(id)
.setDname("id+=>" + id + "没有对应信息,null--@Hystrix")
.setDb_source("no this dataDept in Mysql");
}
}
-----------------------------------------------
//启动类
@SpringBootApplication
@EnableEurekaClient//在服务启动后自动注册到Eureka中
@EnableDiscoveryClient//服务发现
@EnableHystrix //添加对熔断的支持
public class SpringcloudProviderDeotHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudProviderDeotHystrixApplication.class, args);
}
熔断图解
一个请求过来掉很多服务
万一 I 服务蹦了
所有的请求都会都在这里,就会雪崩
所以需要熔断,加个备份文件
降级
@FeignClient(value = "SPRINGCLOUE-PEOVIDER-DEPT",fallbackFactory = DeptChlientServiceFallbackFactory.class)
public interface DeptChlientService {
@GetMapping("/dept/get/{id}")
public Dept queryByaId(@PathVariable("id") Long id);
@GetMapping("/dept/list")
public List<Dept> queruAll();
@PostMapping("dept/add")
public boolean addDept02(Dept dept);
}
--------------------------------------------------------------------------------
@Component
public class DeptChlientServiceFallbackFactory implements FallbackFactory {
@Override
public DeptChlientService create(Throwable cause) {
return new DeptChlientService() {
@Override
public Dept queryByaId(Long id) {
return new Dept().setDeptno(id)
.setDname("id=>"+id+"没有对应的信息,客户端提供了降级的信息,这个服务现在已经被关闭")
.setDb_source("没有数据");
}
@Override
public List<Dept> queruAll() {
return null;
}
@Override
public boolean addDept02(Dept dept) {
return false;
}
};
}
}
Feign无法使用feign:hystrix:enabled: true的问题
客户端配置
# 新版本改成了
feign:
circuitbreaker:
enabled: true #开启降级
服务熔断,和服务降级概念
服务熔断:服务端~某个服务超时或者异常,引起熔断,保险丝
服务降级:客户端、从整体网站请求负载考虑,当某个服务熔断或者关闭之后,服务将不再被调用此时在客户端,我们可以准备一个 FaLlbackFactory,返回一个默认的值(缺省值),整体的服务水平下降了但是,好歹能用·比直接挂掉强
监控
<!--完善监控信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Unable to connect to Command Metric Stream. 错误
在配置类加上
hystrix:
dashboard:
proxy-stream-allow-list: localhost
或者
hystrix:
dashboard:
proxy-stream-allow-list: *
Hystrix dashboard怎么看:
一线
整图说明: