使用RateLimiter可查看另外两篇文章:
spring cloud网关(zuul)使用RateLimiter限流,使用jMeter性能测试高并发
spring cloud微服务间限流,使用jMeter性能测试高并发
导入包,pom.xml配置
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.4.1</version>
</dependency>
初始化限流规则,示例是在启动类初始化,也可在其他地方编写。
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
init();
SpringApplication.run(ZuulApplication.class, args);
}
/**
* 初始化限流
*/
private static void init(){
List<FlowRule> rules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
//资源名称
flowRule.setResource("service-order");
//限流类型
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//每秒2 QPS
flowRule.setCount(2);
rules.add(flowRule);
FlowRuleManager.loadRules(rules);
}
}
方案1:使用Filter
网关过滤器编写相关逻辑
@Component
public class SentinelFilter extends ZuulFilter {
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
Entry entry = null;
try{
entry = SphU.entry("service-order");
//业务逻辑
System.out.println("正常请求");
}catch (Exception e){
System.out.println("限流了");
}finally {
if(entry != null){
entry.exit();
}
}
return null;
}
}
注意Entry选择:阿里巴巴包下:com.alibaba.csp.sentinel.Entry
方案2:使用注解
新增服务类:
@Service
public class SentinelService {
/**
* 正常请求
* @return
*/
@SentinelResource(value = "service-order",blockHandler = "fail")
public String success(){
System.out.println("正常请求!");
return "success";
}
/**
* 阻塞
* @return
*/
public String fail(BlockException e){
System.out.println("被限流了");
return "fail";
}
}
编写controller测试类:
@RestController
@RequestMapping("/limit")
public class LimitTestController {
@Autowired
private SentinelService sentinelService;
@RequestMapping("/limitTest")
public String limitTest(){
// return "1111111";
return sentinelService.success();
}
}
在启动类增加注入bean:
@Bean
public SentinelResourceAspect sentinelResourceAspect(){
return new SentinelResourceAspect();
}
初始化限流规则与方案1一致。