基于Redis+Lua脚本实现分布式限流组件封装的方法
来源:脚本之家
2023-01-01 09:25:26
0浏览
收藏
在数据库实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《基于Redis+Lua脚本实现分布式限流组件封装的方法》,聊聊Redislua脚本、分布式限流组件,希望可以帮助到正在努力赚钱的你。
创建限流组件项目

pom.xml文件中引入相关依赖
org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-aop com.google.guava guava 18.0
在resources目录下创建lua脚本 ratelimiter.lua
--
-- Created by IntelliJ IDEA.
-- User: 寒夜
--
-- 获取方法签名特征
local methodKey = KEYS[1]
redis.log(redis.LOG_DEBUG, 'key is', methodKey)
-- 调用脚本传入的限流大小
local limit = tonumber(ARGV[1])
-- 获取当前流量大小
local count = tonumber(redis.call('get', methodKey) or "0")
-- 是否超出限流阈值
if count + 1 > limit then
-- 拒绝服务访问
return false
else
-- 没有超过阈值
-- 设置当前访问的数量+1
redis.call("INCRBY", methodKey, 1)
-- 设置过期时间
redis.call("EXPIRE", methodKey, 1)
-- 放行
return true
end
创建RedisConfiguration 类
package com.imooc.springcloud;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
/**
* @author 寒夜
*/
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(
RedisConnectionFactory factory) {
return new StringRedisTemplate(factory);
}
@Bean
public DefaultRedisScript loadRedisScript() {
DefaultRedisScript redisScript = new DefaultRedisScript();
redisScript.setLocation(new ClassPathResource("ratelimiter.lua"));
redisScript.setResultType(java.lang.Boolean.class);
return redisScript;
}
}
创建一个自定义注解
package com.hy.annotation;
import java.lang.annotation.*;
/**
* @author 寒夜
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AccessLimiter {
int limit();
String methodKey() default "";
}
创建一个切入点
package com.hy.annotation;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* @author 寒夜
*/
@Slf4j
@Aspect
@Component
public class AccessLimiterAspect {
private final StringRedisTemplate stringRedisTemplate;
private final RedisScript rateLimitLua;
public AccessLimiterAspect(StringRedisTemplate stringRedisTemplate, RedisScript rateLimitLua) {
this.stringRedisTemplate = stringRedisTemplate;
this.rateLimitLua = rateLimitLua;
}
@Pointcut(value = "@annotation(com.hy.annotation.AccessLimiter)")
public void cut() {
log.info("cut");
}
@Before("cut()")
public void before(JoinPoint joinPoint) {
// 1. 获得方法签名,作为method Key
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
AccessLimiter annotation = method.getAnnotation(AccessLimiter.class);
if (annotation == null) {
return;
}
String key = annotation.methodKey();
int limit = annotation.limit();
// 如果没设置methodkey, 从调用方法签名生成自动一个key
if (StringUtils.isEmpty(key)) {
Class[] type = method.getParameterTypes();
key = method.getClass() + method.getName();
if (type != null) {
String paramTypes = Arrays.stream(type)
.map(Class::getName)
.collect(Collectors.joining(","));
log.info("param types: " + paramTypes);
key += "#" + paramTypes;
}
}
// 2. 调用Redis
boolean acquired = stringRedisTemplate.execute(
rateLimitLua, // Lua script的真身
Lists.newArrayList(key), // Lua脚本中的Key列表
Integer.toString(limit) // Lua脚本Value列表
);
if (!acquired) {
log.error("your access is blocked, key={}", key);
throw new RuntimeException("Your access is blocked");
}
}
}
创建测试项目

pom.xml中引入组件

application.yml配置
spring: redis: host: 192.168.0.218 port: 6379 password: 123456 database: 0 application: name: ratelimiter-test server: port: 10087
创建controller
package com.hy;
import com.hy.annotation.AccessLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 寒夜
*/
@RestController
@Slf4j
public class Controller {
private final com.hy.AccessLimiter accessLimiter;
public Controller(com.hy.AccessLimiter accessLimiter) {
this.accessLimiter = accessLimiter;
}
@GetMapping("test")
public String test() {
accessLimiter.limitAccess("ratelimiter-test", 3);
return "success";
}
// 提醒! 注意配置扫包路径(com.hy路径不同)
@GetMapping("test-annotation")
@AccessLimiter(limit = 1)
public String testAnnotation() {
return "success";
}
}
开始测试,快速点击结果如下


今天带大家了解了Redislua脚本、分布式限流组件的相关知识,希望对你有所帮助;关于数据库的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
通过kubesphere部署redis的方法
- 上一篇
- 通过kubesphere部署redis的方法
- 下一篇
- Redis常用数据类型命令实例汇总
评论列表
-
- 甜美的墨镜
- 这篇博文真及时,太详细了,写的不错,码住,关注老哥了!希望老哥能多写数据库相关的文章。
- 2023-01-12 22:49:23
查看更多
最新文章
-
- 数据库 · Redis | 11小时前 |
- Redis TOPK.COUNT 怎样读取候选项的近似计数
- 340浏览 收藏
-
- 数据库 · Redis | 18小时前 | Redis · Sorted Set · redis 有序集合 BZMPOP 阻塞消费
- Redis BZMPOP 怎样阻塞等待多个排名集合的数据
- 315浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis LCS 怎样读取两个字符串的公共子序列位置
- 327浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis SORT_RO 怎样只读排序列表中的数值
- 218浏览 收藏
-
- 数据库 · Redis | 18小时前 | Redis · 缓存 · WEIGHTS Count-Min Sketch Redis CMS.MERGE
- Redis CMS.MERGE 怎样给计数草图设置合并权重
- 326浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis LPOS 怎样定位列表中重复值的位置
- 217浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis TDIGEST.BYRANK 怎样按排名查询分位摘要
- 217浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis CMS.INFO 怎样读取计数草图的宽度与深度
- 304浏览 收藏
-
- 数据库 · Redis | 18小时前 | Redis · redis 分位数 TDIGEST.TRIMMED_MEAN TDigest 截尾均值
- Redis TDIGEST.TRIMMED_MEAN 怎样计算指定分位区间的均值
- 137浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis BITFIELD_RO 怎样只读提取打包整数
- 176浏览 收藏
-
- 数据库 · Redis | 18小时前 | Redis · 缓存设计 · redis limit rev 有序集合 BYSCORE Sorted Set ZRANGESTORE BYLEX
- Redis ZRANGESTORE 怎样保存一段有序集合排名结果
- 232浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis ZDIFF 怎样找出排名集合之间的成员差集
- 168浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 747次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 741次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 825次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 793次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 621次使用
查看更多
相关文章
-
- 基于Redis实现分布式锁的方法(lua脚本版)
- 2022-12-29 444浏览

