使用sentinel核心库进行服务熔断降级

基本配置可以参考使用sentinel核心库进行流量控制

1. 定义资源

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.demo.sentinel.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

public static final String DEGRADE_RESOURCE_NAME = "degrade";

2. 初始化服务降级规则

@PostConstruct
    public void initDegradeRule()
    {
        List<DegradeRule> degradeRules = new ArrayList<>();

        DegradeRule degradeRule = new DegradeRule();
        // 资源名称
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        // 按异常数
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        // 数量
        degradeRule.setCount(2);
        // 统计时长(时间窗口),单位毫秒,默认值1000毫秒
        degradeRule.setStatIntervalMs(60 * 1000);                 
        // 最小请求数
        degradeRule.setMinRequestAmount(2);        
        // 熔断时长设置,单位为秒
        degradeRule.setTimeWindow(10);                  
        degradeRules.add(degradeRule);

        DegradeRuleManager.loadRules(degradeRules);
    }

3. 定义降级处理

public User blockHandlerForDegrade(String id, BlockException exception)
{
    return new User("发生降级了");
}

 4. 应用降级规则

    @RequestMapping(value = "/degrade")
    @SentinelResource(value = DEGRADE_RESOURCE_NAME,entryType = EntryType.IN,
             fallback = "blockHandlerForDegrade",
             blockHandler = "blockHandlerForDegrade")
    public User degrade(String id)
    {
        System.out.println("test");  
        int i = 1 / 0;
        return new User("normal");
    }

熔断降级用于保护服务调用方,避免服务调用方由于服务提供方故障导致的调用方出现频繁调用等待而导致的问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值