开发工具idea,开发技术spring cloud
我的学习借鉴了 https://blog.csdn.net/sky786905664/article/details/78995068
作者 Sky786905664 的一些文章
本节我们在之前的service-ribbon上进行改造
不懂得可以看
spring cloud 基础知识清单
首先在什么时候需要断路器的存在,如图所示:
正常情况下消费AB两个服务应该是正常响应返回的
然后突然B服务挂掉了,那么就不能成功的响应,但是我们还是会一直的去请求这个服务,导致一直报错
那么这个时候我们就需要用到断路器,只要一直发生异常我们就不再去疯狂的请求实现业务逻辑,我们可以告诉调用者说服务挂了,然后把错误的请求记录一下以来弥补损失。
那么断路器首先需要加上断路器依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动器上加上@EnableHystrix注解开启断路器,启动类如下:
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableEurekaClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
// 开启负载均衡
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
service代码不变:
public interface HelloService {
public String hiService(String name);
}
impl实现层代码需要加一个处理异常的方法:
@Service
public class HelloServiceImpl implements HelloService {
@Autowired
RestTemplate restTemplate;
@Override
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://eurekaclient/index/hi?name=" + name, String.class);
}
// 返回说已经断开,发生了异常导致断开
public String hiError(String name) {
return "hi," + name + ",sorry,error!";
}
}
启动注册中心全部eureka-server 和 eureka-client (eureka-client启动两个才能看出负载均衡)
访问地址:http://localhost:8084/hi?name=forezp
此时两个eureka-client正常启动是能够进行负载均衡的,如图:
此时我们停掉一个eureka-client:
8083的就会变成
说明断路器生效了