局部服务降级(在服务提供方设置)
一般服务降级放在消费端,即 消费者端 ,但是提供者端一样能使用。
首先提供者,即8001 先从自身找问题,设置自身调用超时的峰值,峰值内正常运行,超出峰值需要有兜底的方法处理,作服务降级fallback
(1)在8001服务提供方引入Hystrix依赖
/**
* 可以正常访问的方法
* @param id
* @return
*/
public String paymentInfo_Ok(Integer id){
return "线程池:" + Thread.currentThread().getName() + " ,paymentInfo_OK,id:" + id;
}
/**
超时访问的方法
*/
@HystrixCommand(fallbackMethod = "timeoutHandler",commandProperties = {
//设置峰值,超过 3 秒,就会调用兜底方法,这个时间也可以由feign控制
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfo_Timeout(Integer id){
int interTime = 5;
//int i = 10/0;
try{
TimeUnit.SECONDS.sleep(interTime);
}catch (Exception e){
e.printStackTrace();
}
return "线程池:" + Thread.currentThread().getName() + " ,paymentInfo_Timeout,id:" + id + "耗时" + interTime + "秒钟";
}
// 定义服务出现异常之后,兜底的方法
public String timeoutHandler(Integer id){
return “服务异常,请重试…”;
}
}
(3)在启动类上开启服务熔断
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker //开启服务熔断
public class HystrixPaymentApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixPaymentApplication.class,args);
}
}
(4)启动8001服务测试
(5)现在我们改动服务方里面的代码(模拟服务出现异常,而不是服务调用超时)
总结:
我们发现。只要是我们服务不可用了(调用超时、内部错误),都可以用降级来处理。
局部服务降级(在消费方设置)
(1)将服务提供方关于所有服务降级的设置全部去掉
(2)在服务消费方引入hsytrix依赖
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
(3)在启动类上开启服务熔断
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients //开启Feign客户端
@EnableCircuitBreaker//开启熔断器
public class HystrixOrderApplication80 {
public static void main(String[] args) {
SpringApplication.run(HystrixOrderApplication80.class,args);
}
}
(4)在controller编写降级逻辑
@RestController
@Slf4j
@SuppressWarnings(“all”)
public class OrderController {
@Autowired
OrderService orderService;
@GetMapping("/consumer/payment/hystrix/{id}")
public String paymentInfo_OK(@PathVariable(“id”)Integer id){
log.info(“paymentInfo_OKKKKOKKK”);
return orderService.paymentInfo_OK(id);
}
@HystrixCommand(fallbackMethod = “handeException”, commandProperties = {
//设置峰值,超过 1.5 秒,就会调用兜底方法
@HystrixProperty(name=“execution.isolation.thread.timeoutInMilliseconds”, value = “1500”)
})
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable(“id”)Integer id){
log.info(“paymentInfo_timeout”);
return orderService.paymentInfo_Timeout(id);
}
public String handeException(Integer id){
return "服务调用异常,请稍后再试.....";
}
}
(5)启动测试
(6)修改服务提供方代码