前言
- 进行服务熔断之前,请务必确保本地有服务降级演示的代码,为了演示方便本次以
hystrix-client8011
一个项目进行操作,不在启动Eureka集群。服务降级演示环境
服务熔断
-
hystrix-client8011
服务添加接口及业务类public interface UserServiceInter { String success(String userId); String timeOut(String userId); /** *熔断演示接口 */ String breaker(Integer id); }
@Service public class UserServiceInterImpl implements UserServiceInter { /** * circuitBreaker.enabled:是否开启断路器 * circuitBreaker.requestVolumeThreshold:请求次数 * circuitBreaker.sleepWindowInMilliseconds:时间窗口期 * circuitBreaker.errorThresholdPercentage:失败率 * 一句话说明白:断路器打开的情况下,如果接口在10秒内有10次请求, * 但这10次请求其中有半数以上都失败了,那么断路器跳闸并熔断该方法 * 此时正确的请求也不会调用到该方法了,而是直接走降级的方法 * 过一段时间发现请求都正常了,断路器会慢慢的打开放行一些请求,直到完全打开! * 更多属性可以参考:HystrixPropertiesManager类 */ @HystrixCommand(fallbackMethod = "fallbackBreaker", commandProperties = { @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), }) @Override public String breaker(Integer id) { if(id < 0){ throw new RuntimeException("id必须大于零"); } return "查询成功,业务流水号是:"+ UUID.randomUUID().toString(); } /** *降级方法 */ public String fallbackBreaker(Integer id){ return "id必须大于零,id="+id; }
-
Controller增加请求资源
@RestController @Slf4j public class TestController { @Value("${server.port}") private String port; @Autowired private UserServiceInter userServiceInter; @GetMapping(value = "service/breaker/{id}") public String breaker(@PathVariable("id") Integer id){ return userServiceInter.breaker(id); }
-
效果如下
-
这里只做基本的入门介绍,更多详细细节请参看官网Hystrix官网介绍