一、Controller
@RestController
@RequestMapping("/test/")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("test")
public String test() {
String str = testService.findByName("test");
return str;
}
@RequestMapping("test_fall")
public String testFall() {
String str = testService.findByName2("test_fall");
return str;
}
@RequestMapping("test2")
public String test2() {
return "test2";
}
}
二、Service
@Service
@Slf4j
public class TestServiceImpl implements TestService {
// 记录访问次数
private int count = 0;
/**
* 限流
* @param str
* @return
*/
@SentinelResource(value = "findByName", blockHandler = "findByNameBlockHandler")
@Override
public String findByName(String str) {
return "findByName: " + str;
}
public String findByNameBlockHandler(String str, BlockException blockException) {
return "限流成功";
}
/**
* 降级
* @param str
* @return
*/
@SentinelResource(value = "findByName2", fallback = "findByNameFallback")
@Override
public String findByName2(String str) {
// 保证count为奇数时异常,偶数时不异常
if ((count++ & 1) == 1) {
throw new RuntimeException("人为制造异常");
} else {
return str;
}
}
public String findByNameFallback(String str, Throwable throwable) {
if (throwable instanceof RuntimeException) {
log.error("访问失败,原因是:" + throwable.getMessage());
return "访问失败,原因是:" + throwable.getMessage();
} else if (throwable instanceof DegradeException) {
DegradeException e = (DegradeException) throwable;
DegradeRule rule = e.getRule();
int time = rule.getTimeWindow();
log.error("访问被降级,预计[" + time + "]秒内无法访问");
return "访问被降级,预计[" + time + "]秒内无法访问";
} else {
return str;
}
}
}
三、限流
- @SentinelResource的value,即为nacos中配置的source。
- blockHandler为限流抛出异常实现处理函数,该函数的传参必须与资源点的传参一样,并且最后加上
BlockException
异常参数;同时,返回类型也必须一样。
nacos配置:
[
{
"resource": "findByName",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
三、断流降级
- @SentinelResource的value,即为nacos中配置的source。
- fallback为降级抛出异常实现处理函数,该函数的传参必须与资源点的传参一样,同时返回类型也必须一样。可以额外选填一个 Throwable 类型的参数用于接收对应的异常。
快速访问:http://localhost:9010/test/test_fall