0.9.0.RELEASE版本的spring cloud alibaba sentinel限流、降级处理实例

  先看服务提供方的,咱们在原来的sentinel实例(参见0.9.0.RELEASE版本的spring cloud alibaba sentinel实例)上加上限流、降级处理,三板斧只需在最后那一斧controller类中作以下修改:html

 @Slf4j @RestController static class TestController { @Autowired private TestService testService; @GetMapping("/hello") public String hello() { return testService.hello(); } @GetMapping("/hey") public String hey() throws InterruptedException {return testService.hey(); } }

  再新增一个service类,咱们把@SentinelResource挪到这里,并在注解里指定限流、降级的方法:spring

import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Slf4j @Service public class TestService { @SentinelResource(value = "hello", blockHandler = "helloBlock") public String hello() { return "hello"; } public String helloBlock(BlockException ex) { return "hello block"; } @SentinelResource(value = "hey", fallback = "heyFallback") public String hey() throws InterruptedException {
     Thread.sleep(2000);
return "hey"; } public String heyFallback() { return "hey fallback"; } }

  注意限流、降级方法(helloBlock、heyFallback)都须要与原方法参数、返回类型保持一致(限流参数多一个BlockException)。降级的超时是看@SentinelResource所在方法的,因此睡两秒的逻辑也跟着这个注解走,从以前的controller挪到service来。限流、降级规则和jmeter都同以前配置,咱们再用jmeter测试下:app

 

 

相关文章
相关标签/搜索