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

 更新时间:2024年10月11日 12:00:12   作者:HBLOGA  
在Java的微服务生态中,对于服务保护组件,像springcloud的Hystrix,springcloud alibaba的Sentinel,以及当Hystrix停更之后官方推荐使用的Resilience4j,所以本文给大家介绍了Spring Boot集成Resilience4J实现限流/重试/隔离,需要的朋友可以参考下

1.前言

本篇文章主要讲述基于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-demo
  jackson.serialization.indent_output: true
 
management:
  endpoints.web.exposure.include:
    - '*'
  endpoint.health.show-details: always
  health.circuitbreakers.enabled: true
 
resilience4j:
  circuitbreaker:
    configs:
      default:
        registerHealthIndicator: true
        slidingWindowSize: 10
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 3
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 5s
        failureRateThreshold: 50
        eventConsumerBufferSize: 10
 
 
  ratelimiter: 
    instances:
      ratelimitApi:
        limit-for-period: 5 
        limit-refresh-period: 1s 
        timeout-duration: 100ms 
  retry:
    instances:
      backendA:
        maxAttempts: 3
        waitDuration: 10s
        enableExponentialBackoff: true
        exponentialBackoffMultiplier: 2
        retryExceptions:
          - org.springframework.web.client.HttpServerErrorException
          - java.io.IOException
  bulkhead:
    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 calls
 at 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 cause
 
org.springframework.web.client.HttpServerErrorException: 101 SWITCHING_PROTOCOLS
 at 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

以上就是Spring Boot集成Resilience4J实现限流/重试/隔离的详细内容,更多关于SpringBoot集成Resilience4j的资料请关注脚本之家其它相关文章!

相关文章

  • 面试Spring中的bean线程是否安全及原因

    面试Spring中的bean线程是否安全及原因

    这篇文章主要为大家介绍了面试中常问的Spring中bean线程是否安全及原因,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • Java线程安全中的单例模式

    Java线程安全中的单例模式

    这篇文章主要介绍了Java线程安全中的单例模式,需要的朋友可以参考下
    2015-02-02
  • Java实现自定义LinkedList类的示例代码

    Java实现自定义LinkedList类的示例代码

    LinkedList类跟ArrayList类不同,它通过指针以及结点的操作对链表进行增删改查。本文就来和大家分享下Java如何为实现自定义LinkedList类,需要的可以参考一下
    2022-08-08
  • SpringBoot接口限流的实现方法小结

    SpringBoot接口限流的实现方法小结

    在一个高并发系统中对流量的把控是非常重要的,当巨大的流量直接请求到我们的服务器上没多久就可能造成接口不可用,不处理的话甚至会造成整个应用不可用,所以我们需要接口限流,本文给大家介绍了SpringBoot接口限流的实现方法,需要的朋友可以参考下
    2024-10-10
  • Java中string和int的互相转换问题

    Java中string和int的互相转换问题

    本文通过实例代码给大家详细介绍了Java中string和int的互相转换问题,感兴趣的朋友一起看看吧
    2017-10-10
  • SpringBoot之Java配置的实现

    SpringBoot之Java配置的实现

    这篇文章主要介绍了SpringBoot之Java配置的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • Java 实现链表结点插入

    Java 实现链表结点插入

    这篇文章主要介绍了Java 实现链表结点插入操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • springboot整合redis集群过程解析

    springboot整合redis集群过程解析

    这篇文章主要介绍了springboot整合redis集群过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • Java线程休眠的5种方法

    Java线程休眠的5种方法

    这篇文章主要介绍了Java线程休眠的5种方法,分别是Thread.sleep、TimeUnit、wait、Condition、LockSupport,下面文章将对这五种方法进行详细讲解,需要的小伙伴可以参考一下
    2022-05-05
  • java微信开发API第三步 微信获取以及保存接口调用凭证

    java微信开发API第三步 微信获取以及保存接口调用凭证

    这篇文章主要为大家详细介绍了java微信开发API第二步,微信获取以及保存接口调用凭证,感兴趣的小伙伴们可以参考一下
    2016-06-06

最新评论