所有代码都在github上:https://github.com/demonruin/cloud2020/tree/master
服务降级就是指服务器忙,请稍候再试,不让客户端等待并立刻返回一个友好提示,fallback
哪些情况会触发降级:程序运行异常,超时,服务熔断触发服务降级,线程池/信号量打满也会导致服务降级;
服务降级分为 服务端降级 和 客户端降级,好比一双筷子,你可以夹肉,也可以夹菜,不过一般是用来在客户端降级使用,具体情况具体分析使用。下面分别举例在服务端降级和 客户端降级代码演示。有个前提啊,就是项目中已经加入了Hystrix的包依赖支持,酌情选择添加
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
服务端降级
1、需要使用@HystrixCommand,设置兜底即fallback降级方法,设置拦截异常信息。8001服务正常timeout时间为6s,但是服务降级做了5秒等待限制,超过了就不再等待,进行服务降级,调用fallback方法;
package com.king.springcloud.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* created by king on 2020/4/16 3:22 下午
*/
@Service
public class PaymentHystrixService {
/**
* 成功访问
*
* @param id
* @return
*/
public String getOk(Integer id) {
return "线程池:" + Thread.currentThread().getName() + " ID:" + id + "\t 访问成功";
}
/**
* 访问超时
*
* @param id
* @return
* 5000是指5s
*/
@HystrixCommand(fallbackMethod ="paymentFallback_handler",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
public String getTimeout(I