服务的健康状况 = 请求失败数 / 请求总数
)决定的。当断路器开关关闭时请求可以通过,一但服务器健康状况低于设定阈值断路器就会打开,请求会被禁止通过。当断路器处于打开状态时,一段时间后会进入半开状态,这时只允许一个请求通过,如果该请求成功熔断器恢复到关闭状态,如果调用失败断路器继续保持打开。 添加maven依赖
在 SpringCloud 服务消费者(RestTemplate+Ribbon) 基础上对service-ribbon项目进行修改。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
@Service public class HelloServiceRibbonSer { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "helloError") public String helloServiceRibbon(String helloName) { return restTemplate.getForObject("http://say-hello/sayHello?helloName="+helloName,String.class); } public String helloError(String helloName) { return "hello,"+helloName+",error!"; } }
@Autowired private HelloServiceRibbonSer helloServiceRibbonSer; @GetMapping("/ribbonHello") public String ribbonHelloCtr(@RequestParam("helloName")String helloName){ return helloServiceRibbonSer.helloServiceRibbon(helloName); }
在helloServiceRibbon方法的头上加了@HystrixCommand(fallbackMethod = "helloError")注解,代表对这个方法使用了Hystrix相关的功能,fallbackMethod属性是调用回调之后的处理方法。
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient //向服务中心注册 @EnableHystrix //启动Hystrix public class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run(ServiceRibbonApplication.class, args); } }
启动项目
启动注册中心和service-ribbon,不启动say-hello项目(服务提供者),在浏览器地址栏访问 http://localhost :3333/ribbonHello?helloName=aaa发现调用了fallbackMethod中的方法。
修改项目
修改 SpringCloud 服务消费者(Feign) 项目。Feign是自带断路器的,只需要在FeignClient的接口的注解中加上fallback的指定类就行了。
@FeignClient(value = "say-hello",fallback = SayHelloFeignSerHiHystric.class) public interface SayHelloFeignSer { @RequestMapping(value = "/sayHello",method = RequestMethod.GET) String feignSayHelloSer(@RequestParam(value = "helloName") String helloName); }
@Component public class SayHelloFeignSerHiHystric implements SayHelloFeignSer{ @Override public String feignSayHelloSer(String helloName) { return "发生错误 !"+helloName; } }
#打开断路器,D版本之后默认关闭 feign.hystrix.enabled=true
@FeignClient(value = "say-hello",fallbackFactory = HystrixFallBackFactory.class/*fallback = SayHelloFeignSerHiHystric.class*/) public interface SayHelloFeignSer { @RequestMapping(value = "/sayHello",method = RequestMethod.GET) String feignSayHelloSer(@RequestParam(value = "helloName") String helloName); }
public interface UserFeignWithFallBackFactoryClient extends SayHelloFeignSer { }
@Component public class HystrixFallBackFactory implements FallbackFactory<SayHelloFeignSer> { @Override public SayHelloFeignSer create(Throwable throwable) { return new SayHelloFeignSer(){ @Override public String feignSayHelloSer(String helloName) { return "error"; } @Override public String manyParamsSer(String userName, String userPassword) { return "error"; } @Override public Object objParamsCtr(Object user) { return "error"; } }; } }