Spring Boot - 利用Resilience4j-RateLimiter进行流量控制和服务降级

文章目录

  • Resilience4j概述
  • Resilience4j官方地址
  • Resilience4j-RateLimiter
  • 微服务演示
    • Payment processor
      • POM
      • 配置文件
      • Service
      • Controller
    • Payment service
      • POM
      • Model
      • Service
      • RestConfig
      • Controller
      • 配置
      • 验证
  • 探究 Rate Limiting
    • 请求三次 ,观察
    • 等待15秒
    • 连续访问6次

在这里插入图片描述


Resilience4j概述

Resilience4J 是一个针对 Java 8 应用程序的轻量级容错和弹性库。它设计用于在分布式系统中的服务之间提供弹性和容错性。Resilience4J 的名字来源于它提供的核心功能,即让系统(服务)能够“弹性”(resilient)地应对各种失败情况,包括网络问题、第三方服务故障等。

Resilience4J 提供了以下功能:

  1. 断路器(Circuit Breaker):当检测到服务异常或超时,断路器会打开,阻止进一步的请求发送到该服务。一段时间后(通常是秒级),断路器会进入半开状态,允许一个测试请求通过以检查服务是否恢复。如果请求成功,断路器关闭;如果失败,断路器会再次打开。
  2. 限流(Rate Limiter):限制进入系统的请求速率,防止系统过载。这可以通过令牌桶算法或滑动窗口算法实现。
  3. 隔离(Isolation):通过信号量或线程池隔离不同的服务调用,防止一个服务的失败影响到其他服务。
  4. 超时(Timeouts):为服务调用设置超时时间,超过时间后会触发超时异常。
  5. 重试(Retry):在遇到特定异常时自动重试服务调用,可以配置重试次数和间隔。
  6. 缓存(Caching):提供缓存机制,以避免重复执行计算密集型或远程调用。

Resilience4J 的一大特点是它的轻量级特性,它只使用了 Vavr 库(一个函数式编程库),没有其他外部库依赖。这使得它在集成到现有系统时非常方便,且性能开销小。

Resilience4J 设计上易于配置,支持通过代码、配置文件或运行时参数进行配置。它也支持通过 actuator 模块与 Spring Boot 的监控和管理特性集成。

由于 Resilience4J 的这些特性和优势,它在现代分布式系统和微服务架构中得到了广泛应用,尤其是在需要高可用性和弹性的环境中。


Resilience4j官方地址

https://resilience4j.readme.io/

在这里插入图片描述

https://github.com/resilience4j/resilience4j

在这里插入图片描述


Resilience4j-RateLimiter

https://resilience4j.readme.io/docs/ratelimiter

在这里插入图片描述

RateLimiter 的默认实现是 AtomicRateLimiter ,它通过 AtomicReference 管理其状态。 AtomicRateLimiter.State 是完全不可变的。

功能点:

  • Warm-Up Period: 当启动应用程序或重置后,可能会有一个预热期,在此期间速率限制器逐渐增加允许的请求速率。这是为了防止启动后流量突然激增,从而可能导致系统过载。

  • Steady State: 预热期结束后,速率限制器进入稳定状态。在此阶段,速率限制器根据配置的速率限制允许请求通过。例如,如果将限制设置为每分钟 100 个请求,则速率限制器将允许大约每 0.6 秒一个请求。

  • Limit Exceeded: 如果传入请求速率超过配置的限制,速率限制器立即开始拒绝超出的请求。

  • Replenishing Tokens: 速率限制器以与配置的限制相对应的速率持续补充“Token”。每个允许的请求消耗一个令牌。如果系统未充分利用允许的速率,则未使用的令牌会累积,从而允许偶尔爆发请求。

  • Cooldown Period: 如果速率限制器因超出速率限制而拒绝请求,则可能存在一个冷却期,在此期间速率限制器会再次逐渐增加允许的请求速率。这是为了防止限制放宽后流量突然激增。


微服务演示

在这里插入图片描述

我们的演示有 2 个服务,名为支付服务和支付处理器。

在这里插入图片描述

  • 付款服务处理来自购物者的传入付款请求,并将其转发到付款处理器进行处理。
  • 支付处理器处理并发送结果。

我们将对支付服务实施速率限制,以控制传入付款请求的速率。

Payment processor

首先构建支付处理器,因为它是一个依赖服务.

为了演示的目的,将其简化为显示成功消息

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.artisan</groupId>
    <artifactId>payment-processor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>payment-processor</name>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


配置文件

server:
  port: 1010
spring:
  application:
    name: payment-processor

Service

package com.artisan.paymentprocessor.service;
/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
public interface PaymentProcessorService {
    String processPayment(String paymentInfo);
}
package com.artisan.paymentprocessor.service.impl;

import org.springframework.stereotype.Service;

import com.artisan.paymentprocessor.service.PaymentProcessorService;
/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
@Service
public class PaymentProcessorServiceImpl implements PaymentProcessorService {
    @Override
    public String processPayment(String paymentInfo) {
        // Simulated logic to process payment
        return "Payment processed: " + paymentInfo;
    }
}


Controller

package com.artisan.paymentprocessor.controller;

import com.artisan.paymentprocessor.service.PaymentProcessorService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

/**
 * @author artisan
 */
@RestController
@RequestMapping("/api/v1/processor-payment")
@RequiredArgsConstructor
public class PaymentProcessorController {
    private final PaymentProcessorService paymentProcessorService;

    @PostMapping
    public String processPayment(@RequestBody String paymentInfo) {
        return paymentProcessorService.processPayment(paymentInfo);
    }
}

测试一下:

在这里插入图片描述


Payment service

我们将配置 Rate Limiter,并通过 Actuator 监控其状态 。

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.artisan</groupId>
    <artifactId>payment-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>payment-service</name>

    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2022.0.4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
        </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>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


Model

public interface Type {
}

@Data
public class Success implements Type {
    private final String msg;
}



@Data
public class Failure implements Type {
    private final String msg;
}

Service

如何调用外部API -------------->我们这里使用 Spring的 RestTemplate

package com.artisan.paymentservice.service;

import com.artisan.paymentservice.model.Type;

/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
public interface PaymentService {
    Type submitPayment(String paymentInfo);
}

package com.artisan.paymentservice.service.impl;

import com.artisan.paymentservice.model.Failure;
import com.artisan.paymentservice.model.Success;
import com.artisan.paymentservice.model.Type;
import com.artisan.paymentservice.service.PaymentService;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import lombok.RequiredArgsConstructor;

/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
@Service
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {
    private final RestTemplate restTemplate;
    private static final String SERVICE_NAME = "payment-service";
    private static final String PAYMENT_PROCESSOR_URL = "http://localhost:1010/api/v1/processor-payment";


    @Override
    @RateLimiter(name = SERVICE_NAME, fallbackMethod = "fallbackMethod")
    public Type submitPayment(String paymentInfo) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(paymentInfo, headers);
        ResponseEntity<String> response = restTemplate.exchange(PAYMENT_PROCESSOR_URL,
                HttpMethod.POST, entity, String.class);
        Success success = new Success(response.getBody());
        return success;
    }

    private Type fallbackMethod(RequestNotPermitted requestNotPermitted) {
        return new Failure("服务降级: Payment service does not permit further calls");
    }
}

重点关注: @RateLimiter(name = SERVICE_NAME, fallbackMethod = "fallbackMethod")

需要注意这两种方法应该返回相同的数据类型, 所以对两个模型类都使用“Type”来实现。


RestConfig

package com.artisan.paymentservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
@Configuration
public class RestConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Controller

package com.artisan.paymentservice.controller;

import com.artisan.paymentservice.model.Type;
import com.artisan.paymentservice.service.PaymentService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;
/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
@RestController
@RequestMapping("/api/v1/payment-service")
@RequiredArgsConstructor
public class PaymentController {
    private final PaymentService paymentService;
    @PostMapping
    public Type submitPayment(@RequestBody String paymentInfo) {
        return paymentService.submitPayment(paymentInfo);
    }
}


配置

server:
  port: 9090
spring:
  application:
    name: payment-service
management:
  endpoint:
    health:
      show-details: always
  endpoints:
    web:
      exposure:
        include: health
  health:
    ratelimiters:
      enabled: true
resilience4j:
  ratelimiter:
    instances:
      payment-service:
        limit-for-period: 5
        limit-refresh-period: 15s
        timeout-duration: 5s
        register-health-indicator: true
  • limit-for-period:一个“limit-refresh-period”期间允许的请求数
  • limit-refresh-period:指定“limit-for-period”将被重置的持续时间
  • timeout-duration:设置速率限制器允许后续请求的最大等待时间。

这段配置确保了payment-service服务的请求速率不会超过每15秒5次,同时如果请求超过10秒没有响应,则认为请求超时。此外,通过注册健康指标,可以对速率限制器的状态进行监控和管理。


验证

在这里插入图片描述

在这里插入图片描述


探究 Rate Limiting

确保两个服务启动成功

在这里插入图片描述

访问 http://localhost:9090/actuator/health 查看速率限制器详细信息。

在这里插入图片描述


请求三次 ,观察

在这里插入图片描述

http://localhost:9090/api/v1/ payment-service 请求3次 ,然后刷新执行器链接 http://localhost:9090/actuator/health

在这里插入图片描述

等待15秒

等待 15 秒(如果在 API 访问之前开始,时间可能会更短),然后刷新执行器链接 http://localhost:9090/actuator/health,我们将观察到允许的请求重置为 5。

在这里插入图片描述

连续访问6次

API 访问 6 次 http://localhost:9090/api/v1/ payment-service。第 6 个请求将因超出限制而延迟 5 秒。等待期间,刷新 http://localhost:9090/actuator/health 以获取以下详细信息
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/321426.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

安装nodejs出现问题

Error: EPERM: operation not permitted, mkdir… 全局安装express模块进行测试时&#xff1a; npm install express -g出现&#xff1a; 表示nodejs的安装目录无权限&#xff0c;根据错误日志的信息&#xff0c;定位到安装目录下&#xff1a; 点击属性&#xff1a; 点击编…

优先级队列(Priority Queue)

文章目录 优先级队列&#xff08;Priority Queue&#xff09;实现方式基于数组实现基于堆实现方法实现offer(E value)poll()peek()isEmpty()isFull() 优先级队列的实现细节 优先级队列&#xff08;Priority Queue&#xff09; 优先级队列是一种特殊的队列&#xff0c;其中的元素…

Jsqlparser简单学习

文章目录 学习链接模块访问者模式parser模块statement模块Expression模块deparser模块 测试TestDropTestSelectTestSelectVisitor 学习链接 java设计模式&#xff1a;访问者模式 github使用示例参考 测试 JSqlParser使用示例 JSqlParse&#xff08;一&#xff09;基本增删改…

第02章_变量与运算符拓展练习

文章目录 第02章_变量与运算符拓展练习1、辨别标识符2、数据类型转换简答3、判断如下代码的运行结果(难)4、判断如下程序的运行结果5、判断如下程序的运行结果6、Java的基本数据类型有哪些&#xff1f;String是基本数据类型吗&#xff1f;7、语法判断8、char型变量中是否可以存…

LeeCode前端算法基础100题(20)找出字符串中第一个匹配项的下标

一、问题详情: 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。 示例 1: 输入:haystack = "sadbutsad", needle = "s…

【现代密码学】笔记 补充7-- CCA安全与认证加密《introduction to modern cryphtography》

【现代密码学】笔记7-- CCA安全与认证加密《introduction to modern cryphtography》 写在最前面7 CCA安全与认证加密 写在最前面 主要在 哈工大密码学课程 张宇老师课件 的基础上学习记录笔记。 内容补充&#xff1a;骆婷老师的PPT 《introduction to modern cryphtography》…

鸿蒙应用开发学习:让page页面强制横屏

一、学习做了个适合横屏的页面但进入页面后是竖屏显示的 前几天在B站上跟着 黑马程序员的 HarmonyOS4.0开发应用教学视频学习了显式动画&#xff08;animateTo&#xff09;和属性动画&#xff08;animation&#xff09;功能&#xff0c;并参照教学视频的内容做了个小鱼动画。…

助力工业园区作业违规行为检测预警,基于YOLOv7【tiny/l/x】不同系列参数模型开发构建工业园区场景下作业人员违规行为检测识别系统

在很多工业园区生产作业场景下保障合规合法进行作业生产操作&#xff0c;对于保护工人生命安全降低安全隐患有着非常重要的作用&#xff0c;但是往往在实际的作业生产中&#xff0c;因为一个安全观念的淡薄或者是粗心大意&#xff0c;对于纪律约束等意思薄弱&#xff0c;导致在…

绝地求生:【PC】第27赛季第2轮更新公告

各位玩家大家好&#xff01;欢迎收看本期闲游盒更新公告。 正式服维护时间 ※ 下列时间可能会根据维护情况而发生变化。 1月10日上午8:00 – 下午4:30 地图轮换 ※ 地图轮换将于每周三上午10点进行。 ※ 在随机选择地图的地区中&#xff0c;第1周可选择荣都地图&#xff0c…

UML-通信图和交互概览图(通信图和顺序图的区别与联系)

UML-通信图和交互概览图&#xff08;通信图和顺序图的区别与联系&#xff09; 一、通信图简介1.消息2.链接 二、通信图和[顺序图](https://blog.csdn.net/weixin_65032328/article/details/135587782)的联系与区别三、交互概览图四、顺序图转化为通信图练习 一、通信图简介 通…

CSC8021_computer network_The Transport Layer

Role of the transport layer • The transport layer is responsible for providing a reliable end-to-end connection between two application processes in a network • Abstracting away the physical subnet • Does not involve intermediate nodes • Takes a netwo…

2024--Django平台开发-Redis集群(十一)

内容回顾 主从复制。 哨兵&#xff1a;实例启动了&#xff0c;哨兵节点没启动&#xff0c;Python通过redis-py连接报错。一定要确保实例节点和哨兵节点都启动了。 搭建集群用的是虚拟机的多台centos服务器&#xff0c;你在跟着学习的时候&#xff0c;一定要全部都是虚拟机&am…

MySQL面试题2

文章目录 面试题 (9-15) 面试题 (9-15) 09&#xff09;查询学过「张三」老师授课的同学的信息 SELECT s.*,c.cname,t.tname FROM t_mysql_teacher t,t_mysql_student s,t_mysql_course c,t_mysql_score sc WHERE t.tidc.tid and c.cidsc.cid and sc.sids.sid and tname ‘张…

EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测

EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测 目录 EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测预测效果基本介绍程序设计参考资料 预测效果 基…

QLExpress和Groovy对比

原理 Groovy groovy基于JVM运行。 编译时&#xff1a;将源文件编译成class文件后&#xff0c;用java的classLoader加载&#xff1b;运行时&#xff1a;直接用groovy classLoader加载 QLExpress QLExpress将文本解析成AST&#xff0c;用java对象表达后执行。 特点 Groo…

如何用LLM和自有知识库搭建智能agent?

用LangChain建立知识库&#xff0c;文末中也推荐其他方案。 项目源码&#xff1a;ChatPDF实现 LangChain Indexes使用 对加载的内容进行索引&#xff0c;在indexes中提供了一些功能&#xff1a; Document Loaders&#xff0c;加载文档Text Splitters&#xff0c;文档切分V…

android.os.NetworkOnMainThreadException

问题 android.os.NetworkOnMainThreadException详细问题 核心代码如下&#xff1a; import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ja…

【Java】IDEA中的JFormDesigner使用教程

目录 1 安装 JFormDesigner 插件2 JFormDesigner 使用教程2.1 新建JFormDesigner Form时的选项2.2 JFormDesigner Form界面布局2.3 JFormDesigner 常用组件 JFormDesigner 是一款用于设计和创建图形用户界面&#xff08;GUI&#xff09;的插件&#xff0c;它允许开发者使用可视…

鸿蒙Harmony-相对布局(RelativeContainer)详解

成年人的世界&#xff0c;从来没有容易二字&#xff0c;想要什么&#xff0c;就得凭自己的努力去拿&#xff0c;遇到事情就得自己生生的硬抗&#xff0c;希望你即使再辛苦&#xff0c;但还是会选择这滚烫的人生&#xff0c;加油陌生的朋友们 目录 一&#xff0c;定义 二&#x…

瑞_Java开发手册_(一)编程规约

文章目录 编程规约的意义&#xff08;一&#xff09;命名风格&#xff08;二&#xff09;常量定义&#xff08;三&#xff09;代码格式&#xff08;四&#xff09;OOP 规约&#xff08;五&#xff09;日期时间&#xff08;六&#xff09;集合处理&#xff08;七&#xff09;并发…