【121期】面试官:什么是熔断?什么是服务降级?
阅读本文大概需要 5.5 分钟。
来自:blog.csdn.net/qq_41497111/article/details/92067565
服务熔断
服务降级
熔断VS降级
目标一致 都是从可用性和可靠性出发,为了防止系统崩溃; 用户体验类似 最终都让用户体验到的是某些功能暂时不可用;
触发原因不同 服务熔断一般是某个服务(下游服务)故障引起,而服务降级一般是从整体负荷考虑;
Hystrix简介
通过第三方客户端的库来为访问依赖服务时的潜在故障提供保护和控制; 防止在复杂分布式系统中出现级联故障; 快速失败和迅速恢复; 在允许的情况下,提供退路对服务进行优雅降级; 提供近实时的监控、报警和操作控制;
使用Hystrix
引入Hystrix依赖
org.springframework.boot
spring-boot-starter-parent
2.0.6.RELEASE
Finchley.SR2
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
<type>pomtype>
import
修改启动类
@EnableFeignClients
@EnableCircuitBreaker
public class MessageCenterApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MessageCenterApplication.class).web(WebApplicationType.SERVLET).run(args);
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
修改Controller
@GetMapping("/msg/get")
@HystrixCommand(fallbackMethod = "getMsgFallback")
public Object getMsg() {
String msg = messageService.getMsg();
return msg;
}
public Object getMsgFallback() {
return "祝您 2019 猪年大吉,'猪'事如意!";
}
/**
* 获取消息详情
*/
@GetMapping("/api/v1/msg/detail/{id}")
@HystrixCommand(fallbackMethod = "getDetailFallback")
public MessageEntity getDetail(@PathVariable(name = "id") Long id) {
return messageService.getById(id);
}
/**
* 获取消息详情退路
*/
public MessageEntity getDetailFallback(Long id){
return null;
}
Feign结合Hystrix
修改Feign客户端
@FeignClient(name = "message-service", fallback = MessageServiceFallback.class)
public interface MessageServiceClient {
@GetMapping("/api/v1/msg/get")
public String getMsg();
}
创建Fallback处理类
@Component
public class MessageServiceFallback implements MessageServiceClient {
@Override
public String getMsg() {
System.out.println("调用消息接口失败,对其进行降级处理!");
return "消息接口繁忙,请稍后重试!";
}
}
修改配置
feign:
hystrix:
enabled: true
监控Hystrix
启用健康监控
org.springframework.boot
spring-boot-starter-actuator
management:
endpoints:
web:
exposure:
include: hystrix.stream
启用Hystrix-Dashboard
引入Hystrix-Dashboard依赖
org.springframework.cloud
spring-cloud-starter-netflix-hystrix-dashboard
修改启动类
@EnableFeignClients
@SpringCloudApplication
@EnableHystrixDashboard
public class MessageCenterApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MessageCenterApplication.class).web(WebApplicationType.SERVLET).run(args);
}
}
仪表盘界面
参考文章
https://github.com/netflix/hystrix/wiki https://github.com/netflix/hystrix https://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html
推荐阅读:
【118期】面试官:你真的清楚 i = i++和 i = ++i 的区别吗?
微信扫描二维码,关注我的公众号
朕已阅
评论