基本配置可以参考使用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");
}
熔断降级用于保护服务调用方,避免服务调用方由于服务提供方故障导致的调用方出现频繁调用等待而导致的问题。