Spring Cloud Alibaba 之 Sentinel

大家好,我是升仔

引言

在微服务架构中,服务之间的依赖错综复杂。一旦某个服务出现问题,很容易引发连锁反应,导致整个系统瘫痪。Sentinel 就是为了解决这类问题而生的。它通过流量控制、熔断降级等机制,保护服务不被过多流量压垮,同时也确保系统的稳定运行。

实战场景

假设我们有一个商品服务(Product Service)和订单服务(Order Service),订单服务在下单时需要调用商品服务获取商品信息。我们将在商品服务中集成 Sentinel 来实现流量控制。

环境准备
  1. JDK 1.8 或更高版本
  2. Maven 3.6 或更高版本
  3. Spring Boot 2.3.0.RELEASE
  4. Spring Cloud Hoxton.SR6
  5. Spring Cloud Alibaba 2.2.1.RELEASE
项目创建
  1. 创建一个 Spring Boot 项目,添加 spring-cloud-starter-alibaba-sentinel 依赖。

  2. 配置文件 application.yml 中添加 Sentinel 的配置。

    spring:
    cloud:
    sentinel:
    transport:
    dashboard: localhost:8080 # Sentinel 控制台地址

商品服务(Product Service)
  1. 创建 ProductController 类,提供一个获取商品信息的接口。

    @RestController
    @RequestMapping("/product")
    public class ProductController {

    复制代码
     @GetMapping("/{productId}")
     public String getProductInfo(@PathVariable String productId) {
         // 模拟业务逻辑
         return "Product info of " + productId;
     }

    }

  2. 添加 Sentinel 的资源保护。可以使用 @SentinelResource 注解。

    @GetMapping("/{productId}")
    @SentinelResource(value = "getProductInfo")
    public String getProductInfo(@PathVariable String productId) {
    // 业务逻辑
    }

集成 Sentinel Dashboard
  1. 下载并启动 Sentinel Dashboard。
  2. 运行商品服务,它会自动连接到 Sentinel Dashboard。
  3. 通过 Sentinel Dashboard 可以对资源进行流量控制设置。

测试与验证

  1. 启动商品服务,访问商品信息接口。
  2. 通过 Sentinel Dashboard 设置流量控制规则,如 QPS 阈值。
  3. 模拟高并发访问,验证流量控制效果。

总结

Sentinel 在微服务架构中扮演着守门人的角色,有效防止了系统因流量过载而崩溃。通过对服务的保护,Sentinel 帮助我们实现了系统的高可用和稳定性。在实际的微服务项目中,Sentinel 的集成和使用是保障系统稳定性的关键步骤。

最后说一句(求关注,求赞,别白嫖)

最近无意间获得一份阿里大佬写的刷题笔记,一下子打通了我的任督二脉,进大厂原来没那么难。

这是大佬写的,7701页的BAT大佬写的刷题笔记,让我offer拿到手软

本文已收录于我的技术网站,next-java.com, 有大厂完整面经,工作技术等经验分享

求一键三连:点赞、分享、收藏

点赞对我真的非常重要!在线求赞,加个关注非常感激

相关推荐
咖啡不甜不好喝1 天前
sentinel踩坑记录
sentinel·springcloud
她说..1 天前
Spring AOP 操作日志框架(CV可用)
java·jvm·spring·springboot·springcloud
better_liang3 天前
每日Java面试场景题知识点之-分布式事务处理
java·微服务·面试·springcloud·分布式事务
ruleslol7 天前
Spring Cloud Gateway 断言完全讲解
springcloud
whltaoin7 天前
【 Java微服务 】Spring Cloud Alibaba :Nacos 注册中心与配置中心全攻略(含服务发现、负载均衡与动态配置)
java·微服务·nacos·springcloud·注册中心·配置中心
灰小猿12 天前
分布式项目集成TLog实现轻量级日志链路追踪
java·分布式·springcloud·tlog·日志链路追踪
最后11113 天前
lamp-cloud 5.7.0 发布,新增缓存清理 + 修复优化全覆盖
java·后端·spring·缓存·springboot·springcloud
漂流幻境13 天前
Spring cloud gateway 跨域配置与碰到的问题
java·gateway·springcloud·跨域
小坏讲微服务14 天前
Docker Compose搭建Git仓库私服上传微服务
分布式·git·docker·微服务·容器·springcloud·springalibaba
小坏讲微服务15 天前
Spring Cloud Alibaba整合SkyWalking的监控完整使用
java·微服务·架构·springcloud·监控·skywalking·java微服务