服务熔断->服务端操作
服务降级->客户端操作
有关详情点击查看
熔断的使用
1、引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
2、开启注解支持
@SpringBootApplication
@EnableEurekaClient
//熔断支持
@EnableCircuitBreaker
public class ApplicationProviederDept_8001 {
public static void main(String[] args) {
SpringApplication.run(ApplicationProviederDept_8001.class,args);
}
}
3 、controller层
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
//获取单个员工信息
@GetMapping("/dept/get/{id}")
//熔断
@HystrixCommand(fallbackMethod = "noDept")
public Dept getDept(@PathVariable("id")Long id){
Dept dept = deptService.selectById(id);
if(dept==null){
throw new RuntimeException("");
}
return dept;
}
public Dept noDept(@PathVariable("id") Long id){
//链式操作
return new Dept()
.setDeptno(id)
.setDb_name("id==>"+id+",不存在该用户 null")
.setDb_source("no this database in mysql");
}
}
4、测试
测试前开启一个注册中心和一个消费者
直接访问生产者效果
从消费者路由访问结果:
当断掉注册中心时 访问依旧不会出问题,返回的依然是我们定制的内容
降级
熔断是对单一的请求进行处理,而降级是对一个类进行处理
@FeignClient中有个参数叫fallbackFactory
我们通过继承这个接口实现对出现突然状况时返回我们制定的信息
service
@FeignClient(value = "SPRINGCLOUD-PROVIEDER-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)
@Component
public interface DeptFeignService {
@GetMapping("/dept/all")
public List<Dept> getDeptAll();
//获取单个员工信息
@GetMapping("/dept/get/{id}")
public Dept getDept(@PathVariable("id")Long id);
//添加员工
@RequestMapping("/dept/add")
public String addDept(@RequestBody Dept dept);
}
factory:
//降级
@Component
public class DeptClientServiceFallBackFactory implements FallbackFactory {
@Override
public DeptFeignService create(Throwable throwable) {
return new DeptFeignService() {
@Override
public List<Dept> getDeptAll() {
return null;
}
@Override
public Dept getDept(Long id) {
return new Dept().setDeptno(id).setDb_name("降级").setDb_source("nosql");
}
@Override
public String addDept(Dept dept) {
return null;
}
};
}
}
5、测试
测试步骤:
1.开启生产者和feign消费者及一个注册中心
2.通过消费者访问指定的部门信息,结果正常
3.关掉生产者,继续通过消费者客户端访问,返回依旧有数据,但是不是数据库信息而是我们制定的信息