一、用代码方式进行流量控制
1. 添加依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.0</version>
</dependency>
2. 定义资源名称
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;
private static final String RESOURCE_NAME = "hello";
3. 对资源定义流控规则
@PostConstruct
private static void initFlowRules()
{
List<FlowRule> rules = new ArrayList<>();
# 定义流控规则
FlowRule rule = new FlowRule();
rule.setResource(RESOURCE_NAME);
# QPS流控规则
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
# 每秒次数
rule.setCount(1);
rules.add(rule);
FlowRule ruleUser = new FlowRule();
ruleUser.setResource(USER_RESOURCE_NAME);
ruleUser.setGrade(RuleConstant.FLOW_GRADE_QPS);
ruleUser.setCount(1);
rules.add(ruleUser);
FlowRuleManager.loadRules(rules);
}
4. 业务执行过程中应用规则
@RequestMapping(value="/hello")
public String hello()
{
Entry entry = null;
try {
entry = SphU.entry(RESOURCE_NAME);
String str = "hello world";
return str;
}catch (BlockException e){
return "被流控了";
}
catch (Exception e){
e.printStackTrace();
}
finally {
if(entry != null){
entry.exit();
}
}
return null;
}
如果访问QPS大于每秒1次时,就会抛出流控异常。
二、用注解方式进行流量控制
1. 添加依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.8.0</version>
</dependency>
2. 在启动类或者配置类配置bean
@Bean
public SentinelResourceAspect sentinelResourceAspect()
{
return new SentinelResourceAspect();
}
3. 添加注解
@RequestMapping("/user")
@SentinelResource(value = USER_RESOURCE_NAME, // 设置资源名称
fallback = "fallbackForUser", // 当方法调用出现异常时的降级方法
blockHandler = "blockHanderForUser") // 设置流控处理方法
public User getUser(String id)
{
// int i = 1 / 0;
return new User("test");
}
4. 添加流控处理
public User blockHanderForUser(String id, BlockException ex)
{
ex.printStackTrace();
return new User("流控了");
}
流控方法应该与资源方法保持一致的参数和返回值,只是在参数列表中,增加一个流控异常参数 。
5. 异常降级方法
public User fallbackForUser(String id, Throwable ex)
{
return new User("异常降级了");
}
|