当前位置: 首页 > news >正文

Spring Boot集成Resilience4J实现限流/重试/隔离

1.前言

上篇文章讲了Resilience4J实现熔断功能,文章详见:Spring Boot集成Resilience4J实现断路器功能 | Harries Blog™,本篇文章主要讲述基于Resilience4J实现限流/重试/隔离。

2.代码工程

pom.xml

<dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-spring-boot3</artifactId><version>2.0.2</version>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

限流

@RequestMapping("/hello")
@RateLimiter(name="ratelimitApi",fallbackMethod = "fallback")
public ResponseEntity<String> showHelloWorld(){return new ResponseEntity<>("success",HttpStatus.OK);}
public ResponseEntity fallback(Throwable e){log.error("fallback exception , {}",e.getMessage());return new ResponseEntity<>("your request is too fast,please low down", HttpStatus.OK);
}

重试

@RequestMapping("/retry")
@Retry(name = "backendA")//use backendA ,if throw IOException ,it will be retried 3 times。
public ResponseEntity<String> retry(String name){if(name.equals("test")){i++;log.info("retry time:{}",i);throw  new HttpServerErrorException(HttpStatusCode.valueOf(101));}return new ResponseEntity<>("retry",HttpStatus.OK);
}

隔离

@RequestMapping("/bulkhead")
@Bulkhead(name = "backendA")
public ResponseEntity<String> bulkhead(){return new ResponseEntity<>("bulkhead",HttpStatus.OK);
}

配置文件

spring:application.name: resilience4j-demojackson.serialization.indent_output: truemanagement:endpoints.web.exposure.include:- '*'endpoint.health.show-details: alwayshealth.circuitbreakers.enabled: trueresilience4j:circuitbreaker:configs:default:registerHealthIndicator: trueslidingWindowSize: 10minimumNumberOfCalls: 5permittedNumberOfCallsInHalfOpenState: 3automaticTransitionFromOpenToHalfOpenEnabled: truewaitDurationInOpenState: 5sfailureRateThreshold: 50eventConsumerBufferSize: 10ratelimiter: instances:ratelimitApi:limit-for-period: 5 limit-refresh-period: 1s timeout-duration: 100ms retry:instances:backendA:maxAttempts: 3waitDuration: 10senableExponentialBackoff: trueexponentialBackoffMultiplier: 2retryExceptions:- org.springframework.web.client.HttpServerErrorException- java.io.IOExceptionbulkhead:instances:backendA:maxConcurrentCalls: 10

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.(Resilience4J)

3.测试

1.启动Spring Boot应用程序

测试限流

public class ThreadTest {public static void main(String[] args) {for(int i=0;i<6;i++){new Thread(()->{System.out.println(new RestTemplate().getForObject("http://localhost:8080/hello",String.class));}).start();}}
}

运行main方法

io.github.resilience4j.bulkhead.BulkheadFullException: Bulkhead 'backendA' is full and does not permit further callsat io.github.resilience4j.bulkhead.BulkheadFullException.createBulkheadFullException(BulkheadFullException.java:49) ~[resilience4j-bulkhead-2.0.2.jar:2.0.2]at io.github.resilience4j.bulkhead.internal.SemaphoreBulkhead.acquirePermission(SemaphoreBulkhead.java:164) ~[resilience4j-bulkhead-2.0.2.jar:2.0.2]at io.github.resilience4j.bulkhead.Bulkhead.lambda$decorateCheckedSupplier$0(Bulkhead.java:68) ~[resilience4j-bulkhead-2.0.2.jar:2.0.2]at io.github.resilience4j.bulkhead.Bulkhead.executeCheckedSupplier(Bulkhead.java:471) ~[resilience4j-bulkhead-2.0.2.jar:2.0.2]at io.github.resilience4j.spring6.bulkhead.configure.BulkheadAspect.handleJoinPoint(BulkheadAspect.java:194) ~[resilience4j-spring6-2.0.2.jar:2.0.2]at io.github.resilience4j.spring6.bulkhead.configure.BulkheadAspect.proceed(BulkheadAspect.java:147) ~[resilience4j-spring6-2.0.2.jar:2.0.2]at io.github.resilience4j.spring6.bulkhead.configure.BulkheadAspect.lambda$bulkheadAroundAdvice$1(BulkheadAspect.java:120) ~[resilience4j-spring6-2.0.2.jar:2.0.2]at io.github.resilience4j.spring6.fallback.FallbackExecutor.execute(FallbackExecutor.java:37) ~[resilience4j-spring6-2.0.2.jar:2.0.2]at io.github.resilience4j.spring6.bulkhead.configure.BulkheadAspect.bulkheadAroundAdvice(BulkheadAspect.java:121) ~[resilience4j-spring6-2.0.2.jar:2.0.2]at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:637) ~[spring-aop-6.1.2.jar:6.1.2]

测试重试

访问http://127.0.0.1:8080/retry?name=test

2024-08-03T23:16:32.092+08:00 INFO 5097 --- [resilience4j-demo] [nio-8080-exec-9] c.e.r.controller.HelloWorldController : retry time:1
2024-08-03T23:16:42.120+08:00 INFO 5097 --- [resilience4j-demo] [nio-8080-exec-9] c.e.r.controller.HelloWorldController : retry time:2
2024-08-03T23:17:02.142+08:00 INFO 5097 --- [resilience4j-demo] [nio-8080-exec-9] c.e.r.controller.HelloWorldController : retry time:3
2024-08-03T23:17:02.165+08:00 ERROR 5097 --- [resilience4j-demo] [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.HttpServerErrorException: 101 SWITCHING_PROTOCOLS] with root causeorg.springframework.web.client.HttpServerErrorException: 101 SWITCHING_PROTOCOLSat com.et.resilience4j.controller.HelloWorldController.retry(HelloWorldController.java:37) ~[classes/:na]at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:352) ~[spring-aop-6.1.2.jar:6.1.2]at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196) ~[spring-aop-6.1.2.jar:6.1.2]

测试隔离

public class ThreadTest {public static void main(String[] args) {/*  for(int i=0;i<6;i++){new Thread(()->{System.out.println(new RestTemplate().getForObject("http://localhost:8080/hello",String.class));}).start();}*/for(int i=0;i<11;i++){new Thread(()->{System.out.println(new RestTemplate().getForObject("http://localhost:8080/bulkhead",String.class));}).start();}}
}

运行main方法

2024-08-03T23:17:36.943+08:00 ERROR 5097 --- [resilience4j-demo] [nio-8080-exec-5] c.e.r.controller.HelloWorldController : fallback exception , RateLimiter 'ratelimitApi' does not permit further calls

http://www.lryc.cn/news/414225.html

相关文章:

  • 谷粒商城实战笔记-119~121-全文检索-ElasticSearch-mapping
  • Java 并发编程:Java 线程池的介绍与使用
  • ubuntu上安装HBase伪分布式-2024年08月04日
  • Mojo的特征与参数(参数化部分)详解
  • C++数组、vector求最大值最小值及其下标
  • 内网安全:多种横向移动方式
  • 搭建 STM32 网关服务器的全流程:集成嵌入式 C++、TCP/IP 通信、Flash 存储及 JWT 认证(含代码示例)
  • 一款免费强大的电脑锁屏工具,中文绿色免安装
  • Python | Leetcode Python题解之第319题灯泡开关
  • 前端Web-JavaScript(上)
  • 【积累】Python的类
  • Golang | Leetcode Golang题解之第318题最大单词长度乘积
  • 【感想】支持八股文在面试的应用
  • B - 02-计算球的体积 51Nod - 3266
  • Qt pro文件详解
  • JavaFX布局-ButtonBar
  • 【C++程序设计】——利用数组处理批量数据(二)
  • 使用 1panel面板 部署 php网站
  • Windows调大虚拟内存来代替升级物理运行内存(RAM)真的有用吗?
  • [Unity] ShaderGraph实现DeBuff污染 溶解叠加效果
  • java算法day28
  • vue实现歌词滚动效果
  • 【算法设计题】合并两个非递减有序链表,第1题(C/C++)
  • Vue前端工程
  • 什么是药物临床试验?
  • 编译和汇编的区别
  • C# 设计倒计时器、串口助手开发
  • 图论① dfs | Java | LeetCode 797,Kama 98 邻接表实现(未完成)
  • Mac安装nvm以及配置环境变量
  • AUTOSAR实战教程-使用DET来发现开发错误