{"id":28314648,"url":"https://github.com/julxxy/http-rate-limiter-spring-parent","last_synced_at":"2025-06-26T08:04:02.280Z","repository":{"id":65509082,"uuid":"566418261","full_name":"julxxy/http-rate-limiter-spring-parent","owner":"julxxy","description":"一个用于支持springboot项目http请求限制的starter，通过识别客户端传来token值(具有唯一标志性)来实现：同一个用户在一定的时间频次内最多只能点击N次特定接口的功能，使用redisson内置非公平锁实现","archived":false,"fork":false,"pushed_at":"2023-07-08T18:09:50.000Z","size":148,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-24T09:33:09.693Z","etag":null,"topics":["api-limit","http-request-restrict","java","redis","spring","spring-boot"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/julxxy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-11-15T16:23:08.000Z","updated_at":"2023-10-15T09:32:50.000Z","dependencies_parsed_at":"2024-10-30T06:49:28.681Z","dependency_job_id":null,"html_url":"https://github.com/julxxy/http-rate-limiter-spring-parent","commit_stats":null,"previous_names":["julxxy/http-rate-limiter-spring-parent"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/julxxy/http-rate-limiter-spring-parent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/julxxy%2Fhttp-rate-limiter-spring-parent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/julxxy%2Fhttp-rate-limiter-spring-parent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/julxxy%2Fhttp-rate-limiter-spring-parent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/julxxy%2Fhttp-rate-limiter-spring-parent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/julxxy","download_url":"https://codeload.github.com/julxxy/http-rate-limiter-spring-parent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/julxxy%2Fhttp-rate-limiter-spring-parent/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262026977,"owners_count":23246953,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-limit","http-request-restrict","java","redis","spring","spring-boot"],"created_at":"2025-05-24T19:10:34.799Z","updated_at":"2025-06-26T08:04:02.274Z","avatar_url":"https://github.com/julxxy.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# http-rate-limiter-spring-boot-starter\n\n[![Maven Central](https://img.shields.io/maven-central/v/io.github.weasley-j/http-rate-limiter-spring-boot-starter)](https://search.maven.org/artifact/io.github.weasley-j/http-rate-limiter-spring-boot-starter)\n\n一个用于支持`springboot`项目`http`请求限制的`starter`，通过识别客户端传来`token`值(具有唯一标志性)\n来实现：同一个用户在一定的时间频次内最多只能点击`N`次特定接口的功能\n\n## 1 映入pom坐标\n\n版本号在`maven`仓库获取\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003eio.github.weasley-j\u003c/groupId\u003e\n  \u003cartifactId\u003ehttp-rate-limiter-spring-boot-starter\u003c/artifactId\u003e\n  \u003cversion\u003e${latest.version}\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n\n\n## 2 应用yaml配置元数据\n\n**这里以`Sa-Token`作为`token`逻辑演示**\n\n### 2.1 [Github示例链接](https://github.com/Weasley-J/http-rate-limiter-spring-parent/blob/main/http-rate-limiter-spring-boot-tests/src/main/resources/application-demo.yml)\n\n```yaml\nspring:\n\n  redis:\n    host: 127.0.0.1\n    port: 6379\n    password: 123456\n    database: 0\n\n  #  Config（组件主体配置）\n  request:\n    restrict:\n      enable: on\n      # 指定要解析的请求头名称列表, 多个满足一个即可作为key, @RateLimit注解里面的'headName'和'cookieName'\n      # 优先级: headName \u003e cookieName \u003e header-keys\n      header-keys:\n        - x-auth-token\n      redis:\n        enable-ssl: off\n        host: ${spring.redis.host}\n        port: ${spring.redis.port}\n        password: ${spring.redis.password}\n        database: ${spring.redis.database}\n\n# Sa Token\nsa-token:\n  enable: true\n  # token名称 (同时也是cookie名称)\n  token-name: x-auth-token\n  # token有效期，单位s 默认30天, -1代表永不过期\n  timeout: 2592000\n  # token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒\n  activity-timeout: -1\n  # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)\n  is-concurrent: true\n  # 在多人登录同一账号时，是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)\n  is-share: true\n  # token风格\n  token-style: simple-uuid\n  # 是否输出操作日志\n  is-log: false\n  plugins:\n    redis:\n      show-banner: true\n      redis-base-prefix: 'uc:'\n      independent-session: true\n      independent-redis:\n        host: ${spring.redis.host}\n        port: ${spring.redis.port}\n        password: ${spring.redis.password}\n        database: ${spring.redis.database}\n```\n\n\n\n**补充：**`Sa-Token`的`pom`坐标（版本号在`maven`仓库获取）\n\n```xml\n\u003c!-- sa-token  --\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ecn.dev33\u003c/groupId\u003e\n    \u003cartifactId\u003esa-token-spring-boot-starter\u003c/artifactId\u003e\n    \u003cversion\u003e${sa-token.version}\u003c/version\u003e\n\u003c/dependency\u003e\n\u003c!-- Sa-Token 整合 Redis （使用 jackson 序列化方式） --\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ecn.dev33\u003c/groupId\u003e\n    \u003cartifactId\u003esa-token-dao-redis-jackson\u003c/artifactId\u003e\n    \u003cversion\u003e${sa-token.version}\u003c/version\u003e\n\u003c/dependency\u003e\n\u003c!-- sa-plugin-redis --\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003eio.github.weasley-j\u003c/groupId\u003e\n    \u003cartifactId\u003esa-plugin-redis-spring-boot-starter\u003c/artifactId\u003e\n    \u003cversion\u003e1.0.5\u003c/version\u003e\n\u003c/dependency\u003e\n        \u003c!-- redis启动器 --\u003e\n\u003cdependency\u003e\n\u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n\u003cartifactId\u003espring-boot-starter-data-redis\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\n### 2.2 注解`@RateLimit`使用示例\n\n一下接口调用前先要调用**登录接口**获取指定的`token`\n\n```java\n/**\n * Rate Limit Demo Controller\n *\n * @author weasley\n * @version 1.0.0\n */\n@Slf4j\n@RestController\n@RequestMapping(\"/api/public/demo\")\npublic class RateLimitDemoController {\n\n    @PostMapping(\"/clickOnce5Seconds\")\n    @RateLimit(value = 5, maxCount = 1, timeUnit = TimeUnit.SECONDS) //5秒内点仅能点击1次\n    public void clickOnce5Seconds() {\n        log.info(\"5秒内点仅能点击1次\");\n    }\n\n    @PostMapping(\"/click2Times10Seconds\")\n    @RateLimit(value = 10, maxCount = 2, timeUnit = TimeUnit.SECONDS) //10秒内仅能点击2次\n    public void click2Times10Seconds() {\n        log.info(\"10秒内仅能点击2次\");\n    }\n\n    @PostMapping(\"/click5Times5Minutes\")\n    @RateLimit(value = 5, maxCount = 5, timeUnit = TimeUnit.MINUTES) //5分钟只能内只能点5次\n    public void click5Times5Minutes() {\n        log.info(\"5分钟只能内只能点5次\");\n    }\n\n    @PostMapping(\"/click2Times10SecondsByHeaderName\")\n    @RateLimit(value = 5, maxCount = 1, timeUnit = TimeUnit.SECONDS, headName = \"x-auth-token\") //5秒内仅能点击1次, 解析请求头\n    public void click2Times10SecondsByHeaderName() {\n        log.info(\"指定headerName: 5秒内仅能点击1次\");\n    }\n\n    @PostMapping(\"/click2Times10SecondsByCookieName\")\n    @RateLimit(value = 10, maxCount = 1, timeUnit = TimeUnit.SECONDS, cookieName = \"x-auth-token\")\n    //10秒内仅能点击2次,解析cookie\n    public void click2Times10SecondsByCookieName() {\n        log.info(\"指定cookieName: 10秒内仅能点击2次\");\n    }\n}\n```\n\n## 3 通过注解装配bean开启功能\n\n```java\nimport annotation.io.github.weasleyj.http.rate.limit.EnableHttpRateLimit;\nimport io.github.weasleyj.satoken.session.annotation.EnableSaIndependentRedisSession;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n/**\n * DEMO APP\n */\n@SpringBootApplication\n@EnableRateLimit //主体注解\n@EnableSaIndependentRedisSession\npublic class HttpRequestRestrictDemoApp {\n\n    public static void main(String[] args) {\n        SpringApplication.run(HttpRequestRestrictDemoApp.class, args);\n    }\n\n}\n```\n\n\n\n## 4 启动应用访问接口观察异常\n\n- 访问登录接口获取`token`\n\n[源码](https://github.com/Weasley-J/http-rate-limiter-spring-parent/blob/main/http-rate-limiter-spring-boot-tests/src/main/java/com/example/request/controller/AuthenticationController.java)\n\nhttp://localhost:8080/api/public/auth/login/token\n\n![image-20221116132427745](https://alphahub-test-bucket.oss-cn-shanghai.aliyuncs.com/image/image-20221116132427745.png)\n\n\n\n接口返回：\n\n```json\n{\n  \"tokenName\": \"x-auth-token\",\n  \"tokenValue\": \"d0d4821c21404465895199be8203222c\",\n  \"isLogin\": true,\n  \"loginId\": \"10086\"\n}\n```\n\n- 使用`API`工具调用限流接口\n\n[源码](https://github.com/Weasley-J/http-rate-limiter-spring-parent/blob/main/http-rate-limiter-spring-boot-tests/src/main/java/com/example/request/controller/RateLimitDemoController.java)\n\n10秒内仅能点击2次: http://localhost:8080/api/public/demo/click2Times10Seconds\n\n![image-20221116132857439](https://alphahub-test-bucket.oss-cn-shanghai.aliyuncs.com/image/image-20221116132857439.png)\n\n**触发限流抛出异常方便开发者进行捕获处理，给前端发返回提示。**\n\n```java\nexception.io.github.weasleyj.http.rate.limit.FrequentRequestException: 操作太过频繁，请稍后再试（接口URI: /api/public/demo/click2Times10Seconds, 10(SECONDS)内仅能请求2次）\n\tat interceptor.io.github.weasleyj.http.rate.limit.DefaultRequestRestrictInterceptor.preHandle(DefaultRequestRestrictInterceptor.java:106) ~[classes/:na]\n\tat org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:148) ~[spring-webmvc-5.3.23.jar:5.3.23]\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1066) ~[spring-webmvc-5.3.23.jar:5.3.23]\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964) ~[spring-webmvc-5.3.23.jar:5.3.23]\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.23.jar:5.3.23]\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.23.jar:5.3.23]\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjulxxy%2Fhttp-rate-limiter-spring-parent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjulxxy%2Fhttp-rate-limiter-spring-parent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjulxxy%2Fhttp-rate-limiter-spring-parent/lists"}