熔断是在服务端,抛出异常的时候,会调用fallback的方法,然后返回提示信息,不是太理解的是感觉这个跟异常处理很像,有什么不同吗?(抛出异常的时候,由handler捕获到,然后返回提示信息,感觉很像,就是不太清楚有什么区别,虽然一个是正常返回,一个是异常返回,不管了,以后要是遇到某种场景要是顿悟的话,再回来改)
首先在父工程中引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
然后copy一个用户模块,改名user-service-hystrix
启动类上加: @EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class,args);
}
}
修改application.yml 的端口号和服务名称
spring:
application:
name: user-service-hystrix
server:
port: 8804
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8888/eureka/
修改用户服务的controller:
@RequestMapping("/v1")
@Controller
public class UserController {
@HystrixCommand(fallbackMethod = "fallback")
@RequestMapping(value = "/user/{pk}")
public ResponseEntity<?> getUserInfo(@PathVariable("pk") long pk){
UserInfoResp userInfos= new UserInfoResp();
userInfos.setNickName("cara liu1");
userInfos.setPk(1L);
userInfos.setPhoneNumber("18814098957");
if(pk <= 0){
throw new RuntimeException();
}
return new ResponseEntity<>(userInfos, HttpStatus.OK);
}
// 熔断后,调用的方法
public ResponseEntity<?> fallback(@PathVariable("pk") long pk){
UserInfoResp userInfos= new UserInfoResp();
userInfos.setNickName("service error,please try again");
return new ResponseEntity<>(userInfos,HttpStatus.OK);
}
}
然后在订单服务中创建一个:RibbonUserServiceHystrix.java
@FeignClient(value = "USER-SERVICE-HYSTRIX")
public interface RibbonUserServiceHystrix {
@RequestMapping(value = "/v1/user/{pk}",method = RequestMethod.GET)
UserInfoResp getUserInfoFeign(@PathVariable("pk") long pk);
}
启动类上加上开启hystrix的注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class,args);
}
}
添加一个调用的接口,修改后为:
@Controller
@RequestMapping("/v1")
public class OrderController {
@Autowired
private RibbonUserService ribbonUserService;
@Autowired
private RibbonUserServiceHystrix ribbonUserServiceHystrix;
@RequestMapping(value = "/order/feign",method = RequestMethod.GET)
public ResponseEntity<?> getOrder(){
UserInfoResp userInfoResp = ribbonUserService.getUserInfoFeign();
return new ResponseEntity<>(userInfoResp, HttpStatus.OK);
}
@RequestMapping(value = "/order/feign/{pk}",method = RequestMethod.GET)
public ResponseEntity<?> getOrder(@PathVariable long pk){
UserInfoResp userInfoResp = ribbonUserServiceHystrix.getUserInfoFeign(pk);
return new ResponseEntity<>(userInfoResp, HttpStatus.OK);
}
}
然后重新启动该订单服务和相应的用户服务,然后调用接口:
GET http://localhost:8803/v1/order/feign/-1
返回结果:
{
"pk": 0,
"nickName": "service error,please try again",
"phoneNumber": null
}