Spring Cloud Alibaba 整合 Sentinel:实现微服务高可用防护
一、Sentinel 简介
Sentinel 是阿里巴巴开源的面向分布式服务架构的流量控制组件,主要提供以下核心功能:
-
流量控制:针对不同的调用关系,以不同的运行指标(如 QPS、线程数、系统负载等)为基准,对资源调用进行流量控制
-
熔断降级:当资源调用出现不稳定(如响应时间变长、异常比例升高)时进行熔断降级
-
系统自适应保护:根据系统负载动态调整流量,保护系统稳定性
-
实时监控和控制面板:提供实时监控和规则配置的 UI 控制台
二、环境准备
本人使用的版本:
-
JDK 1.8
-
Spring Boot 2.7.18
-
Spring Cloud 2021.0.8
-
Spring Cloud Alibaba 2021.0.5.0
-
Sentinel 1.8.8
三、项目搭建与整合
1、新建shop-product 服务
这里就不过多赘述了,如果有需要可以参考我的这篇文章SpringCloud Alibaba微服务工程搭建_搭建spring-cloud-alibaba微服务项目-CSDN博客
2、添加依赖
配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.shop.parent</groupId><artifactId>shop-cloud-service</artifactId><version>1.0-SNAPSHOT</version></parent><groupId>com.shop</groupId><artifactId>shop-product</artifactId><version>0.0.1-SNAPSHOT</version><name>shop-product</name><description>商品服务模块</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--nacos 注册中心--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- sentinel --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><!-- Sentinel Datasource Nacos --><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><version>1.8.6</version></dependency><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.52</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3、配置 Sentinel
server:port: 39698spring:application:name: shop-productcloud:nacos:discovery: #注册中心配置server-addr: 127.0.0.1:8848 # Nacos服务器地址username: nacos # Nacos账号password: nacos # Nacos密码namespace: 89aa8b8a-11fd-48cc-9163-06f1925cae03 # 命名空间IDgroup: DEV_GROUP # 服务分组enabled: true # 是否开启服务注册发现,默认为trueregister-enabled: true # 是否注册服务,默认为trueservice: ${spring.application.name} # 服务名,默认为spring.application.namesentinel:transport:dashboard: localhost:8080 # Sentinel控制台地址eager: true # 是否立即初始化web-context-unify: false #关闭context整合
4、自定义限流异常返回
package com.shop.product.config;import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 自定义限流异常返回** @author XXY* @date 2025-04-24 15:56:13*/
@Slf4j
@Component
public class MyBlockException implements BlockExceptionHandler {@Overridepublic void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {String msg = "系统未知异常!";int status = 429;if (e instanceof FlowException) {msg = "抱歉,请求被限流了!";} else if (e instanceof DegradeException) {msg = "抱歉,请求被降级了!";} else if (e instanceof ParamFlowException) {msg = "抱歉,热点参数限流!";} else if (e instanceof AuthorityException) {msg = "抱歉,请求没有权限!";status = 401;}log.error(msg);httpServletResponse.setContentType("application/json;charset=utf-8");httpServletResponse.setStatus(status);httpServletResponse.getWriter().println("{\"message\": \"" + msg + "\", \"status\": " + status + "}");}
}
5、 启动Sentinel
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
访问 http://localhost:8080
,默认用户名和密码都是 sentinel
。
到这里,整合已经完成了~~~~~~
四、Sentinel 功能分析
1、前期准备
新建一个controller层,写一个接口,访问http://localhost:39698/v1/product/getProduct,刷新Sentinel 控制台就能看到服务。
@GetMapping(value = "/getProduct")public String getProduct() {return "查询商品!";}
2、流量控制
点击簇点链路,找到流控,对请求路径设置流控。
使用jmeter测试接口,观察结果发现,前五个请求成功,后五个请求失败,限流生效。
3、熔断规则
五、常见问题
-
规则不生效:检查是否开启了 Sentinel(
spring.cloud.sentinel.enabled=true
) -
控制台看不到应用:检查应用与控制台的网络连通性,确保应用正确配置了控制台地址
-
注解不生效:确保添加了
@EnableAspectJAutoProxy
注解并引入了sentinel-annotation-aspectj
依赖 -
规则频繁失效:考虑使用动态数据源持久化规则
六、总结
通过 Spring Cloud Alibaba 整合 Sentinel,我们可以轻松为微服务架构添加强大的流量控制、熔断降级和系统保护功能。Sentinel 丰富的功能和灵活的配置方式使其成为微服务治理的重要工具。合理使用 Sentinel 可以有效防止服务雪崩,提高系统的整体稳定性。
希望本文能帮助你快速上手 Sentinel,为你的微服务架构保驾护航!