步骤一:
添加Pom依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
步骤二:
- 在启动类中添加对熔断的支持
//启动类
@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到eureka中
@EnableDiscoveryClient //服务发现
@EnableCircuitBreaker//添加对熔断的支持
public class DeptProviderHystrix_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProviderHystrix_8001.class,args);
}
}
步骤二:
举例:
@RestController //JSON格式传输,直接RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "hystrixGet")//回退的方法
public Dept get(@PathVariable("id") Integer id){
Dept dept = deptService.queryById(id);
if(dept==null){
throw new RuntimeException("Id=>"+id+",不存在该用户,或信息无法找到~");
}
return dept;
}
//备选方案
public Dept hystrixGet(@PathVariable("id") Integer id){
return new Dept().setDeptno(id)
.setDname("id=>"+id+"没有对应的信息,null-@Hystrix")
.setDb_source("no this database in MySQL");
//return new Dept().setDeptno(id)
}
}
当服务出错时,会执行下面的方法区返回值给前台,避免服务报错,影响前台显示。