效果
例子
AController.testA接口调用AService.testA方法
如果我们需要限制这个入口调用AService.testA的次数,则可以通过流控规则来限制
在AService.testA方法上贴上@SentinelResource注解,并设置资源名及降级方法(因为此时是服务报错)
后再去添加流控规则
Controller、Service代码如下
package cn.mb.sentinelconsumer.controller;
import cn.mb.sentinelconsumer.service.AService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AController {
@Autowired
private AService aService;
@GetMapping(value = "/testA")
public String testA() {
return aService.testA();
}
@GetMapping(value = "/testB")
public String testB() {
return aService.testA();
}
}
package cn.mb.sentinelconsumer.service;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
@Service
public class AService {
// 指定资源名,并指定降级方法
@SentinelResource(value = "testA", blockHandler = "testAFallback")
public String testA() {
return "testA";
}
public String testAFallback(BlockException ex) {
return "ex testA";
}
}
结果
多次调用testA则会
多次调用testB
因此可知只对testA入口调用做了限制,其他没有限制;