【黑马SpringCloud微服务开发与实战】(五)微服务保护
本文介绍了微服务架构中的雪崩问题及其解决方案,重点讲解了Sentinel的快速入门和使用方法。内容涵盖:1)雪崩问题原因分析;2)通过Sentinel实现请求限流、线程隔离和熔断降级等解决方案;3)Sentinel的本地启动和与Spring Cloud集成配置;4)演示了自定义Fallback处理异常请求;5)详细说明了如何配置服务熔断规则。Sentinel作为强大的流量控制组件,能有效提高系统稳
·
1.雪崩问题——原因分析



2.雪崩问题——解决方案





3.Sentinel——快速入门

本地启动:从资料里面获取jar包并且把版本后缀去掉和命令的名称一致
java -Dserver.port=8090 -Dcsp.sentinel.dashboard.server=localhost:8090 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

http://localhost:8090 访问sentinel
cart服务整合sentinel
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8090



spring:
cloud:
sentinel:
transport:
dashboard: localhost:8090
http-method-specify: true # 开启请求方式前缀

4.Sentinel——请求限流



用户信息

5.Sentinel——线程隔离






6.Sentinel——Fallback




@Slf4j
public class ItemClientFallback implements FallbackFactory<ItemClient> {
@Override
public ItemClient create(Throwable cause) {
return new ItemClient() {
@Override
public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
log.error("远程调用ItemClient#queryItemByIds方法出现异常,参数:{}", ids, cause);
// 查询购物车允许失败,查询失败,返回空集合
return CollUtils.emptyList();
}
@Override
public void deductStock(List<OrderDetailDTO> items) {
// 库存扣减业务需要触发事务回滚,查询失败,抛出异常
throw new BizIllegalException(cause);
}
};
}
}
放置DefaultFeignConfig中进行声明
@Bean
public ItemClientFallback itemClientFallback(){
return new ItemClientFallback();
}
@FeignClient(value = "item-service",
configuration = DefaultFeignConfig.class,
fallbackFactory = ItemClientFallback.class)
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
@PutMapping("/items/stock/deduct")
void deductStock(@RequestBody List<OrderDetailDTO> items);
}
feign:
okhttp:
enabled: true # 开启OKHttp功能
sentinel:
enabled: true

 |
7.Sentinel——服务熔断



20s后熔断结束后会发送一个请求看商品服务查询是否正常,如果不正常继续熔断,反之。。。。。。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)