15.8.2 按照Url地址限流+后续处理
通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息
- 业务类RateLimitController:
@GetMapping("/rateLimit/byUrl") @SentinelResource(value = "byUrl") public CommonResult byUrl() { return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002")); }
- 配置:
- 测试
疯狂点击http://localhost:8401/rateLimit/byUrl
会返回Sentinel自带的限流处理结果
15.8.3 上面兜底方案面临的问题
1 系统默认的,没有体现我们自己的业务要求。
2 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。
3 每个业务方法都添加一个兜底的,那代码膨胀加剧。
4 全局统一的处理方法没有体现。
15.8.4 客户自定义限流处理逻辑
- 创建CustomerBlockHandler类用于自定义限流处理逻辑
public class CustomerBlockHandler { public static CommonResult handleException(BlockException exception){ return new CommonResult(2020,"自定义的限流处理信息......CustomerBlockHandler"); } }
- 修改RateLimitController
/** * 自定义通用的限流处理逻辑, blockHandlerClass = CustomerBlockHandler.class blockHandler = handleException2 上述配置:找CustomerBlockHandler类里的handleException2方法进行兜底处理 */ /** * 自定义通用的限流处理逻辑 */ @GetMapping("/rateLimit/customerBlockHandler") @SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2") public CommonResult customerBlockHandler() { return new CommonResult(200,"按客户自定义限流处理逻辑"); }
- Sentinel控制台配置:
- 测试:
疯狂访问:http://localhost:8401/rateLimit/customerBlockHandler ,测试后我们自定义的出来了.
- 进一步说明
15.8.5 更多注解属性说明
1.Sentinel主要有三个核心Api
- SphU定义资源
- Tracer定义统计
- ContextUtil定义了上下文
2.自定义Resource
所有的代码都要用try-catch-finally方式进行处理,o(╥﹏╥)o
15.9 服务熔断功能
15.9.1 sentinel整合+Ribbon+fallback
1.启动nacos和sentinel
2.构建提供者9003/9004
- 建Module—cloudalibaba-provider-payment9003/9004
- POM
<dependencies> <!--SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity --> <groupId>com.rg.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <!-- SpringBoot整合Web组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--日常通用jar包配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
YML
server: port: 9003 spring: application: name: nacos-payment-provider cloud: nacos: discovery: server-addr: 192.168.174.128:8848 #配置Nacos地址 management: endpoints: web: exposure: include: '*'
- 主启动
@SpringBootApplication @EnableDiscoveryClient public class PaymentMain9003 { public static void main(String[] args) { SpringApplication.run(PaymentMain9003.class, args); } }
业务类
@RestController public class PaymentController { @Value("${server.port}") private String serverPort; public static HashMap<Long,Payment> hashMap = new HashMap<>(); static { hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181")); hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182")); hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183")); } @GetMapping(value = "/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) { Payment payment = hashMap.get(id); CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment); return result; } }
- 测试地址:http://localhost:9003/paymentSQL/1 ,可以正常访问
3.消费者84
- 建Module—cloudalibaba-consumer-nacos-order84
- POM
<dependencies> <!--SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--SpringCloud ailibaba sentinel --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <!-- 引入自己定义的api通用包,可以使用Payment支付Entity --> <dependency> <groupId>com.rg.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <!-- SpringBoot整合Web组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--日常通用jar包配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
- YML
server: port: 84 spring: application: name: nacos-order-consumer cloud: nacos: discovery: server-addr: 192.168.174.128:8848 sentinel: transport: #配置Sentinel dashboard地址 dashboard: localhost:8888 #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口 port: 8719 ##消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者) service-url: nacos-user-service: http://nacos-payment-provider
- 主启动
@EnableDiscoveryClient @SpringBootApplication public class OrderNacosMain84 { public static void main(String[] args) { SpringApplication.run(OrderNacosMain84.class, args); } }
- 业务类
ApplicationContextConfig
@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } }
4.CircleBreakerController +测试
目的:验证fallback管运行异常,blockHandler管配置违规
- 编写基础代码
@RestController @Slf4j public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Resource private RestTemplate restTemplate; @RequestMapping("/consumer/fallback/{id}") @SentinelResource(value = "fallback") public CommonResult <Payment> fallback(@PathVariable Long id){ CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4){ System.out.println("44444444444"); throw new IllegalArgumentException("IllegalArgumentException,非法参数异常..."); }else if(result.getData()==null){ System.out.println("111111111111111"); throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常..."); } return result; } }
访问: http://localhost:84/consumer/fallback/1 进行测试,测试成功! 访问 http://localhost:84/consumer/fallback/4 跳转至到错误页面.但是这个error页面对用户很不友好
只配置fallback
编码:
@RequestMapping("/consumer/fallback/{id}") @SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常 public CommonResult <Payment> fallback(@PathVariable Long id){ CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4){ throw new IllegalArgumentException("IllegalArgumentException,非法参数异常..."); }else if(result.getData()==null){ throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常..."); } return result; } public CommonResult handlerFallback(@PathVariable Long id,Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444, "兜底异常handlerFallback,exception内容:" + e.getMessage(), payment); }
结果:
图说:
- 只配置blockHandler
编码:
@RequestMapping("/consumer/fallback/{id}") //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常 @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流 public CommonResult <Payment> fallback(@PathVariable Long id){ CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4){ throw new IllegalArgumentException("IllegalArgumentException,非法参数异常..."); }else if(result.getData()==null){ throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常..."); } return result; } public CommonResult handlerFallback(@PathVariable Long id,Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444, "兜底异常handlerFallback,exception内容:" + e.getMessage(), payment); } public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) { Payment payment = new Payment(id,"null"); return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment); }
本例sentinel需配置:
异常超过2次后,断路器打开,断电跳闸,系统被保护
结果:
图说:
- fallback和blockHandler都配置
编码:
@RequestMapping("/consumer/fallback/{id}") //@SentinelResource(value = "fallback") //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常 //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流 @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler") public CommonResult <Payment> fallback(@PathVariable Long id){ CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4){ System.out.println("44444444444"); throw new IllegalArgumentException("IllegalArgumentException,非法参数异常..."); }else if(result.getData()==null){ System.out.println("111111111111111"); throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常..."); } return result; } public CommonResult handlerFallback(@PathVariable Long id,Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444, "兜底异常handlerFallback,exception内容:" + e.getMessage(), payment); } public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) { Payment payment = new Payment(id,"null"); return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment); }
本例sentinel需配置:
结果:
若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。如果没有超出限流规则,则走fallback 逻辑.
图说:
- 忽略属性—exceptionsToIgnore
编码:
@RequestMapping("/consumer/fallback/{id}") //@SentinelResource(value = "fallback") //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback负责业务异常 //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler负责在sentinel里面配置的降级限流 @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class}) public CommonResult <Payment> fallback(@PathVariable Long id){ CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id); if(id==4){ System.out.println("44444444444"); throw new IllegalArgumentException("IllegalArgumentException,非法参数异常..."); }else if(result.getData()==null){ System.out.println("111111111111111"); throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常..."); } return result; } public CommonResult handlerFallback(@PathVariable Long id,Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444, "兜底异常handlerFallback,exception内容:" + e.getMessage(), payment); } public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) { Payment payment = new Payment(id,"null"); return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment); }
本例sentinel无配置
图说:
结果: 程序异常打到前台了,对用户不友好
15.9.2 sentinel整合+Feign+fallback
1.修改84模块:84消费者调用提供者9003,Feign组件一般是消费侧
2.修改代码
- POM
<!--SpringCloud openfeign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
- YML—激活Sentinel对Feign的支持
server: port: 84 spring: application: name: nacos-order-consumer cloud: nacos: discovery: server-addr: 192.168.174.128:8848 sentinel: transport: #配置Sentinel dashboard地址 dashboard: localhost:8888 #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口 port: 8719 ##消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者) service-url: nacos-user-service: http://nacos-payment-provider # 激活Sentinel对Feign的支持 management: endpoints: web: exposure: include: '*' feign: sentinel: enabled: true
- 业务类
带@FeignClient注解的业务接口
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)//调用中关闭9003服务提供者 public interface PaymentService { @GetMapping(value = "/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id); }
PaymentFallbackService类
@Component public class PaymentFallbackService implements PaymentService { @Override public CommonResult<Payment> paymentSQL(Long id) { return new CommonResult<>(444,"服务降级返回,没有该流水信息",new Payment(id, "errorSerial......")); } }
controller
@RestController @Slf4j public class CircleBreakerController { //========================Sentinel结合OpenFeign @Resource private PaymentService paymentService; @GetMapping(value = "/consumer/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){ // if(id==4){ // throw new RuntimeException("没有该id"); // } return paymentService.paymentSQL(id); } }
- 主启动—添加@EnableFeignClients启动Feign的功能
@EnableDiscoveryClient @SpringBootApplication @EnableFeignClients public class OrderNacosMain84 { public static void main(String[] args) { SpringApplication.run(OrderNacosMain84.class, args); } }
3.测试
访问: http://localhost:84/consumer/paymentSQL/1
测试84调用9003,此时故意关闭9003微服务提供者,可以看到84消费侧自动降级,不会被耗死
15.9.3 熔断框架比较
15.10 规则持久化
15.10.1 是什么
一旦我们重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化
15.10.2 怎么玩
将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上sentinel上的流控规则持续有效
15.10.3 实现步骤
- 修改cloudalibaba-sentinel-service8401
- POM
<!--SpringCloud ailibaba sentinel-datasource-nacos --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency>
- YML—添加Nacos数据源配置
添加Nacos业务规则配置
内容解析:
[ { "resource": "/rateLimit/byUrl", "limitApp": "default", "grade": 1, "count": 1, "strategy": 0, "controlBehavior": 0, "clusterMode": false } ] resource:资源名称; limitApp:来源应用; grade:阈值类型,0表示线程数,1表示QPS; count:单机阈值; strategy:流控模式,0表示直接,1表示关联,2表示链路; controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待; clusterMode:是否集群。
启动8401后刷新sentinel发现业务规则有了
15.10.4 测试
- 快速访问测试接口,http://localhost:8401/rateLimit/byUrl ,显示: Blocked By Sentinel(flow limiting)错误 ,说明配置文件生效了
- 停止8401再看sentinel
重新启动8401再看sentinel .
乍一看还是没有,稍等一会儿.多次调用 http://localhost:8401/rateLimit/byUrl 重新配置出现了,持久化验证通过