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

Redis + Lua 实现分布式限流器

文章目录

    • Redis + Lua 限流实现
      • 1. 导入依赖
      • 2. 配置application.properties
      • 3. 配置RedisTemplate实例
      • 4. 定义限流类型枚举类
      • 5. 自定义注解
      • 6. 切面代码实现
      • 7. 控制层实现
      • 8. 测试

相比 Redis事务, Lua脚本的优点:

  • 减少网络开销:使用Lua脚本,无需向Redis 发送多次请求,执行一次即可,减少网络传输
  • 原子操作:Redis 将整个Lua脚本作为一个命令执行,原子,无需担心并发
  • 复用:Lua脚本一旦执行,会永久保存 Redis 中,,其他客户端可复用

Redis + Lua 限流实现

技术栈:自定义注解aopRedis + Lua 实现限流

1. 导入依赖

 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>30.1-jre</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

2. 配置application.properties

spring.redis.host=10.1.61.121
spring.redis.port=6379
spring.redis.password=123456

3. 配置RedisTemplate实例

package com.lihw.lihwtestboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;@Configuration
public class RedisLimiterHelper {@Beanpublic RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {RedisTemplate<String, Serializable> template = new RedisTemplate<>();template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}
}

4. 定义限流类型枚举类

package com.lihw.lihwtestboot.schemas;/*** @explain: 限流类型* @author: lihewei
*/
public enum LimitType {/*** 自定义key*/CUSTOMER,/*** 请求者IP*/IP;
}

5. 自定义注解

  • period表示请求限制时间段
  • count表示在period这个时间段内允许放行请求的次数。
  • limitType代表限流的类型,可以根据请求的IP自定义key,如果不传limitType属性则默认用方法名作为默认key。
package com.lihw.lihwtestboot.anno;
import com.lihw.lihwtestboot.schemas.LimitType;
import java.lang.annotation.*;/*** @explain: 自定义限流注解* @author: lihewei
*/
@Target({ElementType.METHOD, ElementType.TYPE})//作用于方法上
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {/*** 名字*/String name() default "";/*** key*/String key() default "";/*** Key的前缀*/String prefix() default "";/*** 给定的时间范围 单位(秒)*/int period();/*** 一定时间内最多访问次数*/int count();/*** 限流的类型(用户自定义key 或者 请求ip)*/LimitType limitType() default LimitType.CUSTOMER;
}

6. 切面代码实现

package com.lihw.lihwtestboot.aop;
import com.google.common.collect.ImmutableList;
import com.lihw.lihwtestboot.anno.Limit;
import com.lihw.lihwtestboot.schemas.LimitType;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;/*** @explain: 限流切面实现* @author: lihewei
*/
@Aspect
@Configuration
public class LimitInterceptor {private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);private static final String UNKNOWN = "unknown";private final RedisTemplate<String, Serializable> limitRedisTemplate;@Autowiredpublic LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {this.limitRedisTemplate = limitRedisTemplate;}/*** @author lihw* @description 切面*/@Around("execution(public * *(..)) && @annotation(com.lihw.lihwtestboot.anno.Limit)")public Object interceptor(ProceedingJoinPoint pjp) {MethodSignature signature = (MethodSignature) pjp.getSignature();Method method = signature.getMethod();Limit limitAnnotation = method.getAnnotation(Limit.class);LimitType limitType = limitAnnotation.limitType();String name = limitAnnotation.name();String key;int limitPeriod = limitAnnotation.period();int limitCount = limitAnnotation.count();/*** 根据限流类型获取不同的key ,如果不传我们会以方法名作为key*/switch (limitType) {case IP:key = getIpAddress();break;case CUSTOMER:key = limitAnnotation.key();break;default:key = StringUtils.upperCase(method.getName());}ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));try {String luaScript = buildLuaScript();RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);logger.info("Access try count is {} for name={} and key = {}", count, name, key);if (count != null && count.intValue() <= limitCount) {return pjp.proceed();} else {throw new RuntimeException("You have been dragged into the blacklist");}} catch (Throwable e) {if (e instanceof RuntimeException) {throw new RuntimeException(e.getLocalizedMessage());}throw new RuntimeException("server exception");}}/*** @description 编写 redis Lua 限流脚本*/public String buildLuaScript() {StringBuilder lua = new StringBuilder();lua.append("local c");lua.append("\nc = redis.call('get',KEYS[1])");// 调用不超过最大值,则直接返回lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");lua.append("\nreturn c;");lua.append("\nend");// 执行计算器自加lua.append("\nc = redis.call('incr',KEYS[1])");lua.append("\nif tonumber(c) == 1 then");// 从第一次调用开始限流,设置对应键值的过期lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");lua.append("\nend");lua.append("\nreturn c;");return lua.toString();}/*** @description 获取id地址*/public String getIpAddress() {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return ip;}
}

7. 控制层实现

package com.lihw.lihwtestboot.controller;import com.lihw.lihwtestboot.anno.Limit;
import com.lihw.lihwtestboot.schemas.LimitType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicInteger;@RestController
public class LimiterController {private static final AtomicInteger ATOMIC_INTEGER_1 = new AtomicInteger();private static final AtomicInteger ATOMIC_INTEGER_2 = new AtomicInteger();private static final AtomicInteger ATOMIC_INTEGER_3 = new AtomicInteger();@Limit(key = "limitTest", period = 10, count = 3)@GetMapping("/limitTest1")public int testLimiter1() {return ATOMIC_INTEGER_1.incrementAndGet();}@Limit(key = "customer_limit_test", period = 10, count = 3, limitType = LimitType.CUSTOMER)@GetMapping("/limitTest2")public int testLimiter2() {return ATOMIC_INTEGER_2.incrementAndGet();}@Limit(key = "ip_limit_test", period = 10, count = 3, limitType = LimitType.IP)@GetMapping("/limitTest3")public int testLimiter3() {return ATOMIC_INTEGER_3.incrementAndGet();}
}

8. 测试

10s内连续请求三次以上拒绝请求

相关文章:

Redis + Lua 实现分布式限流器

文章目录 Redis Lua 限流实现1. 导入依赖2. 配置application.properties3. 配置RedisTemplate实例4. 定义限流类型枚举类5. 自定义注解6. 切面代码实现7. 控制层实现8. 测试 相比 Redis事务&#xff0c; Lua脚本的优点&#xff1a; 减少网络开销&#xff1a;使用Lua脚本&…...

ruoyi若依框架SpringSecurity实现分析

系列文章 ruoyi若依框架学习笔记-01 ruoyi若依框架分页实现分析 ruoyi若依框架SpringSecurity实现分析 文章目录 系列文章前言具体分析一、项目中的SpringSecurity版本二、登录认证流程分析三、权限鉴定四、退出登录五、SpringSecurity配置类 总结 前言 在ruoyi-vue若依框…...

Habitat环境学习四:Habitat-sim基础用于导航——使用导航网格NavMesh

如何使用导航网格NavMesh 官方教程1、NavMesh基础定义1.1 使用NavMesh的原因1.2 什么是NavMesh 2、NavMesh的使用方法2.1 获取自上而下Top down view视角地图2.2 在NavMesh中进行查询以及随机产生可导航点2.3 查找最短路径2.4 场景加载NavMesh2.5 重新计算并生成NavMesh2.6 什么…...

python学习笔记 -- 字符串

目录 一、输出字符串的格式 二、字符串的一些函数 1、len函数&#xff1a;字符串长度 2、查找字符所在位置index 3、某字符在字符串中的个数count 4、字符切片 对字符串进行翻转 -- 利用步长 5、修改大小写字母&#xff1a; 6、判断开头和结尾 7、拆分字符串 一、输出…...

2024年GPT如何发展?

2023 年&#xff0c;人工智能领域最具影响的莫过于 GPT-4、ChatGPT 了。 ChatGPT 凭一己之力掀起了 AI 领域的热潮&#xff0c;火爆全球&#xff0c;似乎开启了第四次工业革命。 ChatGPT 入选《Nature》2023 年度十大人物&#xff08;Nature’s 10&#xff09;&#xff0c;这…...

从REPR设计模式看 .NET的新生代类库FastEndpoints的威力

📢欢迎点赞 :👍 收藏 ⭐留言 📝 如有错误敬请指正,赐人玫瑰,手留余香!📢本文作者:由webmote 原创📢作者格言:新的征程,我们面对的不仅仅是技术还有人心,人心不可测,海水不可量,唯有技术,才是深沉黑夜中的一座闪烁的灯塔 !序言 又到了一年年末,春节将至…...

前端入门:(五)JavaScript 续

10. 浏览器存储 10.1 Cookie的概念和使用 Cookie是一种存储在用户计算机上的小型文本文件&#xff0c;用于跟踪和识别用户。Cookie通常用于存储用户的偏好设置、会话信息等&#xff0c;可以通过JavaScript进行读取和设置。 // 示例&#xff1a;设置和读取Cookie document.co…...

研究多态恶意软件,探讨网络安全与AI

前言 近期ChatGPT火遍全球&#xff0c;AI技术被应用到了全球各行各业当中&#xff0c;国内外各大厂商也开始推出自己的ChatGPT&#xff0c;笔者所在公司在前段时间也推出了自研的安全GPT&#xff0c;AI技术在网络安全行业得到了很多的应用&#xff0c;不管是网络安全研究人员、…...

linux驱动工作原理

linux或者windows驱动是如何对上和对下工作的&#xff0c;请用中文回答 在Linux系统中&#xff0c;设备驱动程序通过在/dev目录下创建文件系统条目与硬件通信。应用程序通过打开这些文件来获取描述符&#xff0c;以此来与设备交互。驱动程序内部使用主次设备号来标识设备。而在…...

Rust语言入门(第3篇)

引用与借用 上一篇中&#xff0c;我们介绍了rust的所有权概念&#xff0c;若直接传递变量做函数参数&#xff0c;堆上的变量就会失去所有权&#xff0c;而栈上变量则由于复制&#xff0c;仍有所有权。 fn main(){let b 3;makes_copy(b);println!("after using a variab…...

电脑服务器离线安装.net framework 3.5解决方案(错误:0x8024402c )(如何确定当前系统是否安装NET Framework 3.5)

问题环境&#xff1a; 日常服务的搭建或多或少都会有需要到NET Framework 3.5的微软程序运行框架&#xff0c;本次介绍几种不同的安装方式主要解决运行在Windows 2012 以上的操作系统的服务。 NET Framework 3.5 是什么&#xff1f; .NET Framework是微软公司推出的程序运行框架…...

Three.js学习8:基础贴图

一、贴图 贴图&#xff08;Texture Mapping&#xff09;&#xff0c;也翻译为纹理映射&#xff0c;“贴图”这个翻译更直观。 贴图&#xff0c;就是把图片贴在 3D 物体材质的表面&#xff0c;让它具有一定的纹理&#xff0c;来为 3D 物体添加细节的一种方法。这使我们能够添加…...

【Linux】进程学习(二):进程状态

目录 1.进程状态1.1 阻塞1.2 挂起 2. 进程状态2.1 运行状态-R进一步理解运行状态 2.2 睡眠状态-S2.3 休眠状态-D2.4 暂停状态-T2.5 僵尸状态-Z僵尸进程的危害 2.6 死亡状态-X2.7 孤儿进程 1.进程状态 1.1 阻塞 阻塞&#xff1a;进程因为等待某种条件就绪&#xff0c;而导致的…...

Spring Boot 笔记 003 Bean注册

使用Idea导入第三方jar包 在porn.xml种添加的第三方jar包依赖&#xff0c;并刷新 可以在启动类中尝试调用 以上放到启动类中&#xff0c;不推荐&#xff0c;建议创建一个专门定义的类 package com.geji.config;import cn.itcast.pojo.Country; import cn.itcast.pojo.Province;…...

PCIE 参考时钟架构

一、PCIe架构组件 首先先看下PCIE架构组件&#xff0c;下图中主要包括&#xff1a; ROOT COMPLEX (RC) (CPU); PCIE PCI/PCI-X Bridge; PCIE SWITCH; PCIE ENDPOINT (EP) (pcie设备); BUFFER; 各个器件的时钟来源都是由100MHz经过Buffer后提供。一个PCIE树上最多可以有256…...

【开源】JAVA+Vue.js实现在线课程教学系统

目录 一、摘要1.1 系统介绍1.2 项目录屏 二、研究内容2.1 课程类型管理模块2.2 课程管理模块2.3 课时管理模块2.4 课程交互模块2.5 系统基础模块 三、系统设计3.1 用例设计3.2 数据库设计 四、系统展示4.1 管理后台4.2 用户网页 五、样例代码5.1 新增课程类型5.2 网站登录5.3 课…...

计算机网络(第六版)复习提纲29

第六章&#xff1a;应用层 SS6.1 域名系统DNS 1 DNS被设计为一个联机分布式数据库系统&#xff0c;并采用客户服务器方式&#xff08;C/S&#xff09; 2 域名的体系结构 3 域名服务器及其体系结构 A 域名服务器的分类 1 根域名服务器 2 顶级域名服务器&#xff08;TLD服务器&a…...

有道ai写作,突破免费限制,无限制使用

预览效果 文末提供源码包及apk下载地址 有道ai写作python版 import hashlib import time import json import ssl import base64 import uuidfrom urllib.parse import quote import requests from requests_toolbelt.multipart.encoder import MultipartEncoder from Crypto…...

node.js 使用 elementtree 生成思维导图 Freemind 文件

请参阅: java : pdfbox 读取 PDF文件内书签 请注意&#xff1a;书的目录.txt 编码&#xff1a;UTF-8&#xff0c;推荐用 Notepad 转换编码。 npm install elementtree --save 编写 txt_etree_mm.js 如下 // 读目录.txt文件&#xff0c;使用 elementtree 生成思维导图 Free…...

Vue中路由守卫的详细应用

作为一名web前端开发者&#xff0c;我们肯定经常使用Vue框架来构建我们的项目。而在Vue中&#xff0c;路由是非常重要的一部分&#xff0c;它能够实现页面的跳转和导航&#xff0c;提供更好的用户体验。然而&#xff0c;有时我们需要在路由跳转前或跳转后执行一些特定的逻辑&am…...

League Akari:你的英雄联盟智能助手终极指南

League Akari&#xff1a;你的英雄联盟智能助手终极指南 【免费下载链接】League-Toolkit 兴趣使然的、简单易用的英雄联盟工具集。支持战绩查询、自动秒选等功能。基于 LCU API。 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 还在为英雄联盟中的繁琐操…...

智能客服方案库物流JSON格式优化:从数据冗余到高效解析

在智能客服系统中&#xff0c;物流信息的查询与展示是高频核心功能。随着业务增长&#xff0c;我们方案库中存储和传输的物流JSON数据日益庞大。最初为了图省事&#xff0c;我们采用了“全量字段”的设计&#xff0c;即每次接口返回都包含物流单号、状态、时间、承运商、路由节…...

告别鉴权内耗,让每一位Java开发者都能轻松上手

写Java的这些年&#xff0c;无论是初入职场的新手&#xff0c;还是深耕多年的老兵&#xff0c;谁没在「鉴权」上栽过跟头&#xff1f; 熬夜啃Spring Security的复杂配置&#xff0c;对着一堆过滤器链抓耳挠腮&#xff1b;用Shiro做前后端分离项目&#xff0c;为了适配Token模式…...

Llama-3.2V-11B-cot部署详解:自动修复视觉权重加载致命Bug全过程

Llama-3.2V-11B-cot部署详解&#xff1a;自动修复视觉权重加载致命Bug全过程 1. 项目概述 Llama-3.2V-11B-cot是基于Meta Llama-3.2V-11B-cot多模态大模型开发的高性能视觉推理工具&#xff0c;专为双卡RTX 4090环境深度优化。本工具通过自动修复视觉权重加载等核心Bug&#…...

pyNastran:工程仿真领域的Python变革者——打破商业软件垄断的技术突围

pyNastran&#xff1a;工程仿真领域的Python变革者——打破商业软件垄断的技术突围 【免费下载链接】pyNastran A Python-based interface tool for Nastrans file formats 项目地址: https://gitcode.com/gh_mirrors/py/pyNastran 价值定位&#xff1a;重新定义工程仿真…...

提升Blender渲染效率:立方盒反射烘培与材质优化指南

提升Blender渲染效率&#xff1a;立方盒反射烘培与材质优化指南 在3D创作领域&#xff0c;渲染效率与质量始终是设计师面临的核心挑战。Blender作为开源三维软件的代表&#xff0c;其渲染引擎的灵活性与强大功能为艺术家提供了无限可能&#xff0c;但同时也对硬件资源提出了较高…...

CentOS 7下PHP7.4编译安装全攻略:从依赖解决到常见报错处理

CentOS 7下PHP7.4编译安装全攻略&#xff1a;从依赖解决到常见报错处理 在Linux服务器环境中&#xff0c;PHP作为最流行的服务器端脚本语言之一&#xff0c;其安装方式通常有yum安装和编译安装两种选择。对于追求性能优化和功能定制的开发者来说&#xff0c;编译安装PHP7.4无疑…...

终极RPG Maker解密工具:3分钟学会提取游戏资源

终极RPG Maker解密工具&#xff1a;3分钟学会提取游戏资源 【免费下载链接】RPGMakerDecrypter Tool for extracting RPG Maker XP, VX and VX Ace encrypted archives. 项目地址: https://gitcode.com/gh_mirrors/rp/RPGMakerDecrypter 还在为RPG Maker加密文件无法提取…...

EcomGPT-中英文-7B电商模型与数据库课程设计:构建智能电商问答知识库

EcomGPT-中英文-7B电商模型与数据库课程设计&#xff1a;构建智能电商问答知识库 电商平台每天要处理海量的用户咨询&#xff1a;“这件衣服有M码吗&#xff1f;”、“这个手机和昨天看的那个有什么区别&#xff1f;”、“帮我推荐几款适合送长辈的茶叶”。传统客服要么忙不过…...

打卡信奥刷题(3016)用C++实现信奥题 P6334 [COCI 2007/2008 #1] SREDNJI

P6334 [COCI 2007/2008 #1] SREDNJI 题目描述 给定一个长度为 nnn 的 1∼n1\sim n1∼n 的排列 a1,…,ana_1,\dots ,a_na1​,…,an​&#xff0c;请你找出这个排列有多少个长度为奇数的子串的中位数为 BBB。 子串定义&#xff1a;把这个排列从开头&#xff08;可能无&#xff…...