先看服務提供方的,咱們在原來的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