接上一篇:Spring cloud微服务搭建(七)——Feign面向接口编程
服务熔断,是指某个服务超时或异常,引起熔断,起到保险丝的作用。
针对服务方而言,只涉及修改服务提供方。
Maven依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
服务提供方
控制器
-
@HystrixCommand
:用来修饰要熔断的服务方法fallbackMethod
:String类型属性,用于指定有异常抛出时,回调方法名
-
新增回调方法
此处为
hystrixFallback()
。- 回调方法
hystrixFallback()
&被@HystrixCommand
注解的方法queryById()
- 返回类型保持一致
- 参数列表保持一致
- 回调方法
@RestController
public class DepartmentController {
@Autowired
private DeparmentService deparmentService;
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "hystrixFallback")
public Department queryById(@PathVariable("id") int id){
Department department=deparmentService.queryById(id);
if(null==department){
throw new RuntimeException("id--> "+ id);
}
return department;
}
public Department hystrixFallback(@PathVariable("id") int id){
return new Department().setDeptNo(id)
.setDeptName("id-->"+id+" not exists!");
}
}
启动类
新增@EnableHystrix
注解修饰启动类。开启Hystrix限流。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class DepartmentProvider8002 {
public static void main(String[] args) {
SpringApplication.run(DepartmentProvider8002.class,args);
}
}
测试执行
依次启动Eureka服务,服务提供方,基于Feign实现的客户端(消费方)服务。
首先输入http://localhost/consumer/dept/get/3 ,id为3,数据库存在记录,请求服务方的queryById()
方法,正常返回。
在浏览器输入url地址:http://localhost/consumer/dept/get/30,id为30,在数据库中并不存在记录,此时queryById()
方法抛出异常,回调备用方法hystrixFallback()
,显示内容如下。
服务发生异常时,调用了备用方法,实现了服务熔断。
更多:
Spring cloud开发环境搭建(一)——maven依赖
Spring cloud微服务搭建(三)—— Spring cloud服务提供方
Spring cloud微服务搭建(四)——Spring cloud 消费方
Spring cloud微服务搭建(五)——Eureka注册服务