springboot-aop-redis-lua 实现的分布式限流方案

1.自定义限流注解

@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;
}

2. 限流类型

public enum LimitType {/*** 自定义key*/CUSTOMER,/*** 请求者IP*/IP;
}

 3.redis配置

@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. 限流切面实现

/*** @author* @description 限流切面实现* @date 2020/4/8 13:04*/
@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;}/*** @param pjp* @authofuor * @description 切面* @date 2020/4/8 13:04*/@Around("execution(public * *(..)) && @annotation(com..limit.api.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");}}/*** @author xiaofu* @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;");logger.info("====="+lua.toString());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;}
}

上述Lua脚本解释:jdk8在书写脚本的时候需要使用字符串拼接的方式,jdk17以及以后可以使用代码片段书写

local c    //局部变量
c = redis.call('get',KEYS[1])  //从redis获取key执行的次数
if c and tonumber(c) > tonumber(ARGV[1]) then   //获取的key执行的次数是否大于允许的最大值,如果是直接返回,拒绝访问
return c;
end
c = redis.call('incr',KEYS[1])   //key对应的value增加1
if tonumber(c) == 1 then  //当前的key是否是第一次
redis.call('expire',KEYS[1],ARGV[2]) //对key设置过期时间
end
return c;

5.测试例子

package com.xiaofu.limit.controller;import com.xiaofu.limit.api.Limit;
import com.xiaofu.limit.enmu.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(name = "1111", 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();}}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【华为OD机考B卷 | 100分】统计监控、需要打开多少监控器(JAVA题解——也许是全网最详)

前言 本人是算法小白&#xff0c;甚至也没有做过Leetcode。所以&#xff0c;我相信【同为菜鸡的我更能理解作为菜鸡的你们的痛点】。 题干 OD&#xff0c;B 卷 100 分题目【OD 统一考试&#xff08;B 卷&#xff09;】 1. 题目描述 某长方形停车场每个车位上方都有一个监控…

nginx根据不同的客户端设备进行转发请求——筑梦之路

这里主要介绍七层负载方式实现。 环境说明&#xff1a; pc端 web-1 苹果ios端 web-2 安卓Android端 web-3 负载均衡 web-lb 配置示例&#xff1a; pc端&#xff1a; server {listen 9000; #监听9000server_name pc.xxx.com;charset utf-8;location / {root /…

ansible学习笔记分享

yum install ansible -y #安装&#xff0c;注意yum源问题 yum源&#xff1a; yum install epel-release -y mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo.bak >> /dev/null yum clean all rpm -Uvh http://mirrors.ustc.edu.cn/epel/epel-releas…

常见算法-洗扑克牌(乱数排列)

常见算法-洗扑克牌&#xff08;乱数排列&#xff09; 1、说明 洗扑克牌的原理其实与乱数排列是相同的&#xff0c;都是将一组数字&#xff08;例如1∼N&#xff09;打乱重新排列&#xff0c;只不过洗扑克牌多了一个花色判断的动作而已。 初学者通常会直接想到&#xff0c;随…

【Ubuntu】Systemctl控制nacos启动与关闭

要使用 systemctl 来管理 Nacos Server 的启动和停止&#xff0c;你需要创建一个 systemd 服务单元文件。以下是创建和使用 Nacos Server systemd 服务的一般步骤&#xff1a; 创建一个 systemd 服务单元文件&#xff1a; 打开终端并使用文本编辑器创建一个新的 systemd 服务单…

vue2踩坑之项目:Swiper轮播图使用

首先安装swiper插件 npm i swiper5 安装出现错误&#xff1a;npm ERR npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: vue/eslint-config-standard6.1.0 npm ERR! Found: eslint-plugin-vue8.7.1 npm ERR! node_modules/esl…

NPM 常用命令(十)

目录 1、npm prefix 1.1 使用语法 1.2 描述 1.3 示例 2、npm prune 2.1 使用语法 2.1 描述 3、npm publish 3.1 使用语法 3.2 描述 包中包含的文件 4、npm query 4.1 使用语法 4.2 描述 4.3 示例 5、npm rebuild 5.1 使用语法 5.2 描述 6、npm repo 6.1 使…

PyQt5配置踩坑

安装步骤比较简单&#xff0c;这里只说一下我踩的坑&#xff0c;以及希望一些大佬可以给点建议。 一、QtDesigner 这个配置比较简单&#xff0c;直接就能用&#xff0c;我的配置如下图&#xff1a; C:\Users\lenovo\AppData\Roaming\Python\Python311\site-packages\qt5_app…

linux centos Python + Selenium+Chrome自动化测试环境搭建?

在 CentOS 系统上搭建 Python Selenium Chrome 自动化测试环境&#xff0c;需要执行以下步骤&#xff1a; 1、安装 Python CentOS 7 自带的 Python 版本较老&#xff0c;建议使用 EPEL 库或源码安装 Python 3。例如&#xff0c;使用 EPEL 库安装 Python 3&#xff1a; sud…

Django开发之基础篇

Django基础篇 一、Django学习之路由二、Django学习之视图三、Django学习之静态资源 一、Django学习之路由 在 Django 中&#xff0c;路由&#xff08;URL 映射&#xff09;是将请求与视图函数关联起来的关键部分。路由定义了如何将特定的 URL 请求映射到 Django 应用程序中的视…

Selenium进行无界面爬虫开发

在网络爬虫开发中&#xff0c;利用Selenium进行无界面浏览器自动化是一种常见且强大的技术。无界面浏览器可以模拟真实用户的行为&#xff0c;解决动态加载页面和JavaScript渲染的问题&#xff0c;给爬虫带来了更大的便利。本文将为您介绍如何利用Selenium进行无界面浏览器自动…

linux平台源码编译ffmpeg

目录 编译平台 编译步骤 编译平台 中标麒麟 编译步骤 1 从Download FFmpeg 下载源码&#xff0c;我选中了4.2.9版 2 解压 3 在解压后的目录下输入 ./configure --enable-shared --prefix/usr/local/ffmpeg 4 make 5 sudo make install 6 ffmpeg的头文件、可执行程…

MySQL — MySQL请求很慢,如何定位问题?

置顶 学习专栏&#xff1a;【Java后端面试题】 1.Java面试题—基础知识、面向对象、【容器】、IO & 【设计模式】、泛型 & 异常 & 反射 & 注解、快速排序2.Java面试题—并发基础、【同步 & 互斥】、JUC & 并发容器、【线程池】、异步编程、【Lambda表达…

A Survey and Framework of Cooperative Perception 论文阅读

论文链接 A Survey and Framework of Cooperative Perception: From Heterogeneous Singleton to Hierarchical Cooperation 0. Abstract 首次提出统一的 CP&#xff08;Cooperative Percepetion&#xff09; 框架回顾了基于不同类型传感器的 CP 系统与分类对节点结构&#x…

lua 中文字符的判断简介

一般在工作中会遇到中文字符的判断、截断、打码等需求&#xff0c;之前一直没有总结&#xff0c;虽然网上资料也多&#xff0c;今天在这里简单的总结一下。 1 .UTF-8简单描述 UTF-8 是 Unicode 的实现方式之一&#xff0c;其对应关系&#xff08;编码规则&#xff09;如下表所…

【大数据】Apache NiFi 助力数据处理及分发

Apache NiFi 助力数据处理及分发 1.什么是 NiFi &#xff1f;2.NiFi 的核心概念3.NiFi 的架构4.NiFi 的性能预期和特点5.NiFi 关键特性的高级概览 1.什么是 NiFi &#xff1f; 简单的说&#xff0c;NiFi 就是为了解决不同系统间数据自动流通问题而建立的。虽然 dataflow 这个术…

【Linux】 rm命令使用

作为一个程序员 我们经常用到rm -rf * 或者rm -rf XXX 。但是rm -rf 是什么意思不是很清楚&#xff0c;咱们一起来学习一下吧。 rm&#xff08;英文全拼&#xff1a;remove&#xff09;命令用于删除一个文件或者目录。 rm 命令 -Linux手册页 著者 由保罗鲁宾、大卫麦肯齐、理…

Qt的WebEngineView加载网页时出现Error: WebGL is not supported

1.背景 当我在qml中使用WebEngineView加载一个网页时&#xff0c;出现以下错误&#xff1a; Error: WebGL is not supported 2.解决方案 其实这个问题在Qt的帮助文档中已经提及了解决办法&#xff1a; 因此&#xff0c;可以按照下面的步骤操作一下&#xff1a; 2.1.pro文件 …

layui在上传图片在前端处理图片压缩

有的人会遇到需要在前端代码处理图片压缩的问题&#xff0c;下面给大家分享怎么处理。 // 上传图片 var image_src var IsImgDealfalse; layui.upload.render({ elem: "#{tag}{id}", url: sessionStorage.getItem(httpUrlPrefix) /upload/uploadImage, // dataT…

Unity中Shader光强与环境色

文章目录 前言一、实现下图中的小球接受环境光照实现思路&#xff1a;1、在Pass中使用前向渲染模式2、使用系统变量 _LightColor0 获取场景中的主平行灯 二、返回环境中主环境光的rgb固定a(亮度)&#xff0c;小球亮度还随之改变的原因三、获取Unity中的环境光的颜色1、Color模式…