版权声明:菜鸟_zhengke的博客 https://blog.csdn.net/qq_42014192/article/details/89495428
1.基于springcloud(四)服务消费者(rest+ribbon)负载均衡进行修改
https://blog.csdn.net/qq_42014192/article/details/89311319
2.pom.xml依赖 新增
<!--在ribbon使用断路器hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
3.加@EnableHystrix注解开启Hystrix
@SpringBootApplication
//通过注解@EnableEurekaClient 表明自己是一个eurekaclient服务(服务提供者/服务消费者)
@EnableEurekaClient
//通过@EnableDiscoveryClient向服务中心注册
@EnableDiscoveryClient
//@EnableHystrix注解开启Hystrix
@EnableHystrix
public class SpringcloudServiceRibbonHystrixDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudServiceRibbonHystrixDemoApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
4.改造HelloService类,在clientService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了
fallbackMethod熔断方法,熔断方法直接返回了一个字符串。
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
//出现宕机访问error方法
@HystrixCommand(fallbackMethod = "clientError")
public String clientService(String name){
return restTemplate.getForObject("http://SERVICE-CLIENT/client?name="+name,String.class);
}
public String clientError(String name) {
return "client"+name+",sorry,error!";
}
}
测试步骤:
- 启动注册中心
- 启动服务提供者,修改端口号达到集群效果,宕机一个服务
- 启动服务消费者断路器服务测试。
这就说明当 service-client 工程不可用的时候,service-ribbon调用 service-client 的API接口时,会执行快速失败,直接返回一组字符串,而不是等待响应超时,这很好的控制了容器的线程阻塞。