Hystrix 服务降级(超时情景)
Product 微服务项目
@PostMapping("/listForOrder")
public List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return productService.findList(productIdList);
}
Order 微服务项目
package com.imooc.order.controller;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
// 超时配置
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
@GetMapping("/getProductInfoList")
public String getProductInfoList() {
// product 微服务已启动,以及模拟业务时间 2s(sleep替代)
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",
Arrays.asList("157875196366160022"),
String.class);
}
private String defaultFallback() {
return "默认提示:太拥挤了, 请稍后再试~~";
}
}
- 在类上面加注解@DefaultProperties(defaultFallback = "defaulfFallback"),这样调用失败时进入默认的方法。
- 在这里name是超时时间的类,value是秒数,单位是毫秒。 超时时间默认是1秒。所以如果超过1秒会产生服务降级。