Sentinel API、注解、整合Feign

Sentinel API

Sentinel 提供了一系列的 Java API,开发者可以直接在代码中定义资源并设置流量控制、熔断降级等规则。例如:

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

// 定义资源
String resource = "myResource";

// 创建一个资源入口
try (Entry entry = SphU.entry(resource)) {
    // 业务逻辑代码...
} catch (BlockException ex) {
    // 处理被流控的情况(如记录日志、返回错误信息等)
}

// 动态添加流控规则
FlowRule rule = new FlowRule(resource)
        .setCount(10) // 设置限流阈值为每秒10个请求
        .setGrade(RuleConstant.FLOW_GRADE_QPS); // 设置限流模式为QPS模式
FlowRuleManager.loadRules(Arrays.asList(rule));

Sentinel 注解

Sentinel 还提供了 @SentinelResource 注解来简化资源定义和异常处理:

import com.alibaba.csp.sentinel.annotation.SentinelResource;

@Service
public class MyService {

    @SentinelResource(value = "myMethod", blockHandler = "handleException")
    public String myMethod(String param) {
        // 业务逻辑...
        return "Hello, Sentinel!";
    }

    // 异常处理方法
    public String handleException(BlockException ex) {
        // 当 myMethod 被限流或降级时,将调用此方法
        return "Oops, method is blocked by Sentinel";
    }
}

Sentinel 整合 Feign

Feign 是一个声明式的 HTTP 客户端,Spring Cloud Alibaba Sentinel 提供了对 Feign 的支持,可以在客户端进行服务间调用时实现流量控制和熔断降级。

要整合 Sentinel 和 Feign,你需要做以下配置:

  1. 添加依赖:

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. 配置启用 Sentinel 对 Feign 的支持:

    @Configuration
    @EnableFeignClients
    public class FeignConfig {
        @Bean
        public SentinelFeignBuilder sentinelFeignBuilder() {
            return new SentinelFeignBuilder();
        }
    }
    
  3. 在使用 FeignClient 的接口上使用 @SentinelResource 注解定义资源:

    @FeignClient(name = "microservice-provider", configuration = FeignConfig.class)
    public interface ProviderService {
    
        @GetMapping("/provider/api")
        @SentinelResource("providerApi")
        String providerApi();
    }
    

通过以上步骤,Sentinel 将对 Feign 客户端发起的服务间调用提供相应的保护策略。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值