Sentinel如何与Spring Cloud集成?

SentinelSpring Cloud 的集成可以帮助你在微服务架构中实现更细粒度的流量控制、降级和熔断等功能。以下是 Sentinel 与 Spring Cloud 集成的基本步骤和方法:

1. 添加依赖

首先,你需要在你的 Spring Boot 项目中添加 Sentinel 的相关依赖。Sentinel 提供了与 Spring Cloud 集成的 Starter 依赖,简化了集成过程。

Maven 依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>
Gradle 依赖
implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-sentinel:2.2.5.RELEASE'

2. 配置 Sentinel

接下来,你需要在 application.propertiesapplication.yml 文件中配置 Sentinel 相关的属性。

示例配置
# Sentinel 控制台地址
sentinel.transport.dashboard=127.0.0.1:8080

# Sentinel 连接超时时间(毫秒)
sentinel.transport.timeoutMs=10000

# Sentinel 连接端口号
server.port=8081

# Sentinel 端口
sentinel.port=8719

3. 配置 Sentinel 控制台

确保你的 Sentinel 控制台正在运行,并且可以通过配置的地址访问。你可以通过启动 Sentinel 的控制台应用来实现这一点。

启动 Sentinel 控制台

Sentinel 控制台是一个独立的 Java 应用程序,可以通过以下命令启动:

java -jar sentinel-dashboard-*.jar

4. 配置 Sentinel 与 Spring Cloud Gateway 的集成

如果你使用的是 Spring Cloud Gateway 作为网关,可以配置 Sentinel 作为网关的限流和熔断组件。

添加依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-gateway-starter</artifactId>
</dependency>
配置 Sentinel 适配器
spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true
      routes:
        - id: sentinel-route
          uri: lb://your-service-name
          predicates:
            - Path=/api/**
          filters:
            - name: SentinelGatewayFilter
              args:
                controlBehavior: DEFAULT
                fallbackUri: forward:/fallback

5. 使用 @SentinelResource 注解

在你的服务中,可以使用 @SentinelResource 注解来声明需要进行流量控制、降级或熔断的方法。

示例代码
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "handleException")
    public String hello(@RequestParam("name") String name) {
        return "Hello, " + name;
    }

    public String handleException(BlockException ex) {
        return "Request blocked.";
    }
}

6. 配置流量控制规则

你可以在 Sentinel 控制台中手动配置流量控制规则,也可以通过编程方式动态加载规则。

示例代码
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class FlowRuleConfig {

    @PostConstruct
    public void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("hello");
        rule.setCount(10); // 每秒允许通过的最大请求数量
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流模式:QPS
        rules.add(rule);

        // 加载规则
        FlowRuleManager.loadRules(rules);
    }
}

7. 配置降级规则

同样,你可以在 Sentinel 控制台中手动配置降级规则,也可以通过编程方式动态加载规则。

示例代码
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class DegradeRuleConfig {

    @PostConstruct
    public void initDegradeRules() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("hello");
        rule.setCount(10); // 统计窗口大小
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT); // 降级模式:响应时间
        rule.setStatIntervalMs(1000); // 统计间隔时间(毫秒)
        rule.setTimeWindow(10); // 时间窗口大小
        rule.setMinRequestAmount(5); // 最小请求数量
        rule.setCount(3); // 异常比率阈值
        rules.add(rule);

        // 加载规则
        DegradeRuleManager.loadRules(rules);
    }
}

8. 配置熔断规则

同样,你可以在 Sentinel 控制台中手动配置熔断规则,也可以通过编程方式动态加载规则。

示例代码
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class ParamFlowRuleConfig {

    @PostConstruct
    public void initParamFlowRules() {
        List<ParamFlowRule> rules = new ArrayList<>();
        ParamFlowRule rule = new ParamFlowRule();
        rule.setResource("hello");
        rule.setCount(10); // 每秒允许通过的最大请求数量
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流模式:QPS
        rule.setParamIdx(0); // 参数索引
        rules.add(rule);

        // 加载规则
        ParamFlowRuleManager.loadRules(rules);
    }
}

总结

通过以上步骤,你可以将 Sentinel 与 Spring Cloud 集成起来,实现更细粒度的流量控制、降级和熔断功能。Sentinel 提供了丰富的工具和 API,使得开发者可以在微服务架构中更好地管理和保护服务。你可以根据具体的需求选择合适的规则配置方式,并利用 Sentinel 控制台进行可视化管理和监控。

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值