熔斷是在服務端,拋出異常的時候,會調用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
}