一、微服务架构中使用断路器的原因
二、代码实现
1、在Ribbon中使用短路器
1.1、引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
1.2、在Springboot类中增加@EnableHystrix来开启Hystrix
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @EnableHystrix public class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run( ServiceRibbonApplication.class, args ); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
1.3、在服务方法上增加@HystrixCommand(fallbackMethod = "backError"),该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为"hi,"+name+",sorry,error!"
@Service public class HelloService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "backError") public String hiService(String name) { return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class); } public String hiError(String name) { return "hi,"+name+",sorry,error!"; } }
1.4、启动:service-ribbon 工程,当我们访问http://localhost:8764/hi?name=henry,浏览器显示:
hi ,henry,sorry,error!
2、Feign中使用断路器
2.1、配置文件中开启断路器
feign.hystrix.enabled=true
2.2、在FeignClient的SchedualServiceHi接口的注解中加上fallback的指定类就行了
@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class) public interface SchedualServiceHi { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
2.3、SchedualServiceHiHystric需要实现SchedualServiceHi 接口,并注入容器
@Component public class SchedualServiceHiHystric implements SchedualServiceHi { @Override public String sayHiFromClientOne(String name) { return "sorry "+name; } }
2.4、比较开启服务和关闭服务返回的结果