代码信息
本篇文章涉及代码版本
组件 | 版本 |
---|---|
Spring Boot | 2.0.8.RELEASE |
Spring Cloud | Finchley.SR1 |
本篇文章涉及应用
应用 | 说明 |
---|---|
base-eureka | 服务发现 |
base-hystrix | 熔断器 |
整合熔断器
Hystrix熔断器,容错管理工具,旨在通过熔断机制控制服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。
构建maven依赖
熔断器的其他配置可以参照服务提供方的配置,然后只需要新增hystrix的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
application.yml
application配置甚至不需要怎么修改
spring:
application:
name: base-hystrix
server:
port: 8404
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka/
logging:
file: ${spring.application.name}.log
类的配置
启动类
和之前的应用相比需要添加
@EnableCircuitBreaker
注解
@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
远程调用和类降级
此时需要我们一个方法用来请求数据,以及和它对应的降级方法。我们请求测试的base-producer应用的接口
@Log
@Service
public class ClientService {
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate;
/**
* 配置降级方法
* @return
*/
@HystrixCommand(fallbackMethod = "getServiceBack")
public String getService() {
ServiceInstance serviceInstance = loadBalancerClient.choose("base-producer");
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/getService";
log.info(url);
return restTemplate.postForObject(url,null, String.class);
}
public String getServiceBack() {
return "use fallbackMethod";
}
}
测试用的请求类
现在我们编写一个controller稍后来测试我们的服务降级是否发挥作用
@Log
@RestController
public class HystrixController {
@Autowired ClientService clientService;
@RequestMapping(value = "/hystrixGetService",method = RequestMethod.GET)
public String getService() {
return clientService.getService();
}
}
测试
- 首先我们依次启动
base-eureka
,base-producer
,base-hystrix
三个服务
- 然后我们请求base-hystrix的hystrixGetService接口,此时返回结果正确
3. 然后我们停掉base-producer再次请求
此时可以发现返回的就是之前服务降级配置的内容,证明服务降级已经生效。
本篇文章涉及的源码下载地址:https://gitee.com/daifylearn/cloud-learn
ps.上述的所有项目都是可以成功运行的。但是在后期为了实现每个应用端口尽量不冲突会有些许调整,而后续某次作死调整结构和名称可能会导致部分项目无法运行o(╯□╰)o,如果发现请留言我进行修改。