一、SpringCloudAlibaba整合Sentinel
1、引入依赖
引入 Sentinel依赖,包含了 核心库和客户端等依赖。
<dependency> <groupId>com.alibaba.cloud @Autowired private RestTemplate restTemplate; /**
* http://localhost:18084/app-user-sentinel/flow/getOrderByUserId1/1
*
* @param id
* @return
*/ @RequestMapping(value = "/getOrderByUserId1/{id}") public R getOrderByUserId1(@PathVariable("id") Integer id) { log.info("根据userId=" + id + "查询订单信息"); String url = "http://app-order/order/findOrderByUserId/" + id; R result = restTemplate.getForObject(url, R.class); return result; } /**
* http://localhost:18084/app-user-sentinel/flow/getOrderByUserId2/5
*
* @param id
* @return
*/ @RequestMapping(value = "/getOrderByUserId2/{id}") @SentinelResource(value = "/flow/getOrderByUserId2", blockHandler = "blockHandlerForGetOrderByUserId2", fallback = "fallbackForGetOrderByUserId2") public R getOrderByUserId2(@PathVariable("id") Integer id) throws InterruptedException { log.info("根据userId=" + id + "查询订单信息"); if(id == 20){ TimeUnit.SECONDS.sleep(id); } String url = "http://app-order/order/findOrderByUserId/" + id; R result = restTemplate.getForObject(url, R.class); return result; } public R blockHandlerForGetOrderByUserId2(Integer id, BlockException blockEx) { log.info("BlockException。id={}, blockEx = {}", id, blockEx.getMessage()); return R.error(" getOrderByUserId2 方法被流控了。id=" + id); } public R fallbackForGetOrderByUserId2(Integer id, Throwable e) { log.info("业务出异常了。ex = {}", e.getMessage()); return R.error(" getOrderByUserId2 业务出异常了。ex = " + e); } }
访问接口并添加 QPS流控。上面接口 QPS=2,所以,1秒内多次访问会被流控。
可以通过@SentinelResource注解自定义处理异常信息。
也可以新建一个类,实现BlockExceptionHandler接口,统一处理BlockException。
Sentinel 并发控制不负责创建和管理线程池,而是简单统计当前请求上下文的线程数目(正在执行的调用数目),如果超出阈值,新的请求会被立即拒绝,效果类似于信号量隔离。并发数控制通常在调用端进行配置。
设置并发线程数为1。
其他 Sentinel控制台的使用查看官方文档。
– 求知若饥,虚心若愚。
