java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot 使用Sentinel

Springboot 中使用Sentinel的详细步骤

作者:冰糖心158

文章介绍了如何在SpringBoot中使用Sentinel进行限流和熔断降级,首先添加依赖,配置Sentinel控制台地址,定义受保护的资源,配置流控规则,启动Sentinel控制台和SpringBoot应用,最后测试和监控,感兴趣的朋友一起看看吧

在 Spring Boot 中使用 Sentinel 非常方便,Spring Cloud Alibaba 提供了 spring-cloud-starter-alibaba-sentinel 组件,可以快速将 Sentinel 集成到你的 Spring Boot 应用中,并利用其强大的流量控制和容错能力。

下面是一个详细的步骤指南

步骤 1: 添加 Sentinel 依赖

首先,需要在你的 pom.xml 文件中添加 Spring Cloud Alibaba Sentinel 的依赖。确保你已经配置了 Spring Cloud Alibaba 的依赖管理 (spring-cloud-alibaba-dependencies)。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

如果你需要使用 Sentinel 的持久化功能,例如将规则持久化到 Nacos 配置中心,还需要添加相应的依赖,例如:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

步骤 2: 配置 Sentinel

application.propertiesapplication.yml 文件中配置 Sentinel 的基本信息。 至少需要配置 Sentinel 控制台的地址,以便你可以通过控制台查看监控数据和管理规则。

spring:
  application:
    name: your-spring-boot-app # 应用名称,Sentinel 控制台中会显示
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080 # Sentinel 控制台的地址 (默认端口 8080)
        port: 8719 # Sentinel 客户端与控制台通信的端口,默认 8719,可以自定义,避免冲突
# 如果需要持久化规则到 Nacos,还需要配置 Nacos 相关信息
# nacos:
#  config:
#    server-addr: your-nacos-server-address:8848

注意: 你需要先启动 Sentinel 控制台,才能在控制台中看到你的 Spring Boot 应用的监控数据和配置规则。 你可以从 Sentinel 的 GitHub 仓库下载 Sentinel 控制台的 JAR 包并启动。

步骤 3: 定义受保护的资源

在 Spring Boot 中,你可以使用以下方式来定义需要 Sentinel 保护的资源:

方式一:使用 @SentinelResource 注解

这是最常用的方式,通过在方法上添加 @SentinelResource 注解,可以声明该方法为一个受保护的资源。

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
@Service
public class MyService {
    @SentinelResource(value = "myResource", blockHandler = "handleBlock")
    public String doSomething() {
        // 业务逻辑
        return "Success";
    }
    // BlockHandler 方法,用于处理 BlockException,即限流、熔断等 block 情况
    public String handleBlock(BlockException e) {
        return "Blocked by Sentinel: " + e.getClass().getSimpleName(); // 返回被 Sentinel 拦截的提示信息
    }
}

方式二:编程式 API 定义资源

除了注解,你也可以使用 Sentinel 提供的编程式 API 来定义资源,这种方式更加灵活,可以更细粒度地控制资源的入口和出口。

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
@Service
public class MyService {
    public String doSomethingProgrammatically() {
        Entry entry = null;
        try {
            entry = SphU.entry("myProgrammaticResource"); // 定义资源名
            // 被保护的业务逻辑
            return "Success from Programmatic Resource";
        } catch (BlockException e) {
            // 处理 BlockException,例如限流、熔断等
            return "Blocked by Sentinel (Programmatic): " + e.getClass().getSimpleName();
        } catch (Exception ex) {
            // 业务逻辑异常,需要记录到 Sentinel 的异常统计中
            Tracer.traceEntry(entry, ex);
            throw ex;
        } finally {
            if (entry != null) {
                entry.exit(); // 保证 exit() 被调用,否则会导致统计数据不准确
            }
        }
    }
}

步骤 4: 配置流控规则

定义了受保护的资源后,你需要配置流控规则,告诉 Sentinel 如何对这些资源进行保护。 你可以通过以下方式配置规则:

方式一:在 Sentinel 控制台配置

这是最推荐的方式,通过 Sentinel 控制台,你可以可视化地配置和管理规则,实时生效,无需重启应用。

添加“流控”规则

添加“熔断”机制

方式二:在代码中编程式配置规则

你也可以在代码中编程式地配置规则,这种方式更适合自动化配置或单元测试。

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class FlowRuleConfig implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        initFlowRules();
    }
    private void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("myResource"); // 资源名称,与 @SentinelResource 注解中的 value 对应
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 流控类型:QPS
        rule.setCount(2); // QPS 阈值为 2
        rules.add(rule);
        FlowRuleManager.loadRules(rules); // 加载规则
    }
}

步骤 5: 启动 Sentinel 控制台和 Spring Boot 应用

步骤 6: 测试和监控

高级特性 (可选)

Sentinel 还提供了很多高级特性,你可以根据实际需求进行探索和使用,例如:

总结

使用 Spring Cloud Alibaba Sentinel 在 Spring Boot 中实现限流、熔断降级是非常简单的。 通过添加依赖、配置 Sentinel 控制台地址、定义受保护的资源、配置规则,你就可以快速为你的 Spring Boot 应用增加一层强大的保护屏障,提升系统的稳定性和容错能力。 Sentinel 提供的可视化控制台和丰富的特性,也使得流量控制和容错管理更加便捷高效。

到此这篇关于Springboot 中使用Sentinel的详细步骤的文章就介绍到这了,更多相关Springboot 使用Sentinel内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文