基于Redis+Lua脚本实现分布式限流组件封装的方法

 更新时间:2020年10月31日 09:51:58   作者:陌上千寻雪  
这篇文章主要介绍了基于Redis+Lua脚本实现分布式限流组件封装,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

创建限流组件项目

pom.xml文件中引入相关依赖

 <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>com.google.guava</groupId>
 <artifactId>guava</artifactId>
 <version>18.0</version>
 </dependency>
 
 </dependencies>

在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<String, String> 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<Boolean> rateLimitLua;
 
 public AccessLimiterAspect(StringRedisTemplate stringRedisTemplate, RedisScript<Boolean> 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";
 }
 
}

开始测试,快速点击结果如下

到此这篇关于基于Redis+Lua脚本实现分布式限流组件封装的方法的文章就介绍到这了,更多相关Redis+Lua脚本实现分布式限流组件内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!

相关文章

  • Redis批量删除指定前缀的Key两种方法

    Redis批量删除指定前缀的Key两种方法

    redis作为缓存服务器在项目中经常使用,使用redis存储数据时,我们经常会将key分组,这篇文章主要给大家介绍了关于Redis批量删除指定前缀的Key两种方法,需要的朋友可以参考下
    2024-01-01
  • Redis分布式锁与Redlock算法实现

    Redis分布式锁与Redlock算法实现

    在Redis中,可以使用多种方式实现分布式锁,如使用SETNX命令或RedLock算法,本文就来介绍一下Redis分布式锁与Redlock算法实现,感兴趣的可以了解一下
    2023-12-12
  • redis序列化及各种序列化情况划分

    redis序列化及各种序列化情况划分

    本文主要介绍了redis序列化及各种序列化情况划分,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Redis下载部署并加入idea应用的小结

    Redis下载部署并加入idea应用的小结

    这篇文章主要介绍了Redis下载部署并加入idea应用,需要的朋友可以参考下
    2022-10-10
  • Windows下Redis安装配置教程

    Windows下Redis安装配置教程

    这篇文章主要为大家详细介绍了Windows下Redis安装配置教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • 基于redis集群设置密码的实例

    基于redis集群设置密码的实例

    今天小编就为大家分享一篇基于redis集群设置密码的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • SpringBoot整合Mybatis-plus和Redis实现投票功能

    SpringBoot整合Mybatis-plus和Redis实现投票功能

    投票功能是一个非常常见的Web应用场景,这篇文章将为大家介绍一下如何将Redis和Mybatis-plus整合到SpringBoot中,实现投票功能,感兴趣的可以了解一下
    2023-05-05
  • Redis Value过大问题(键值过大)

    Redis Value过大问题(键值过大)

    这篇文章主要介绍了Redis Value过大问题(键值过大),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • redis主从切换导致的数据丢失与陷入只读状态故障解决方案

    redis主从切换导致的数据丢失与陷入只读状态故障解决方案

    这篇文章主要介绍了redis主从切换导致的数据丢失与陷入只读状态故障解决方案的相关资料,需要的朋友可以参考下
    2023-05-05
  • 使用SpringBoot集成redis的方法

    使用SpringBoot集成redis的方法

    这篇文章主要介绍了SpringBoot集成redis的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03

最新评论

?


http://www.vxiaotou.com