所谓降级,就是当某个服务出现异常之后,服务器将不再被调用,此时服务端可以自己准备一个本地的fallback回调,返回一个缺省值。
这样做,虽然服务水平下降,但好歹可用,比直接挂掉要强,当然这也要看适合的业务场景。
启动类:
package com.wangfajun; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; //@SpringBootApplication
//@EnableDiscoveryClient
//@EnableCircuitBreaker //开启断路器
@SpringCloudApplication
public class FajunClientTestApplication { public static void main(String[] args) {
SpringApplication.run(FajunClientTestApplication.class, args);
}
}
服务端代码demo(客户端请求服务端serverMethod方法时,如果服务端宕机或是serverMethod中抛出异常,则将调用defaultFallback方法):
package com.odao.client.controller; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.*; @RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class FeignClientTestController { @HystrixCommand
@GetMapping(value = "serverMethod")
public String serverMethod() {
/*throw new RuntimeException("异常了");*/
return null;
} public String defaultFallback() {
return "太拥挤了";
}
pom:
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>