0.9.0.RELEASE版本的spring cloud alibaba sentinel限流、降级处理实例
先看服务提供方的,我们在原来的sentinel实例(参见0.9.0.RELEASE版本的spring cloud alibaba sentinel实例)上加上限流、降级处理,三板斧只需在最后那一斧controller类中做如下修改:
@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挪到这里,并在注解里指定限流、降级的方法:
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测试下: