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

 更新时间:2020年10月31日 09:51:58   作者:陌上千寻雪  
这篇文章主要介绍了基于Redis+Lua脚本实现分布式限流组件封装,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

创建限流组件项目

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脚本实现分布式限流组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详解如何在Windows上配置和使用Redis持久化功能

    详解如何在Windows上配置和使用Redis持久化功能

    Redis 是一个强大的内存数据库,常用于缓存和实时数据处理,然而,由于其内存特性,一旦服务器重启或故障,存储在 Redis 中的数据可能会丢失,为了确保数据的安全性和持久性,Redis 提供了多种持久化机制,本文将详细介绍如何在 Windows 上配置和使用 Redis 的持久化功能
    2024-08-08
  • Redis用GEO实现附近的人功能

    Redis用GEO实现附近的人功能

    GEO就是Geolocation的简写形式,代表地理坐标,这篇文章主要介绍了Redis用GEO实现附近的人功能,需要的朋友可以参考下
    2024-08-08
  • 详解RedisTemplate下Redis分布式锁引发的系列问题

    详解RedisTemplate下Redis分布式锁引发的系列问题

    这篇文章主要介绍了详解RedisTemplate下Redis分布式锁引发的系列问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • redis与mongodb的区别总结

    redis与mongodb的区别总结

    在本篇文章里小编给大家分享的是关于redis与mongodb的区别的相关知识点内容,有需要的朋友们参考下。
    2019-06-06
  • Redis集群的实现全过程

    Redis集群的实现全过程

    Redis集群的实现方案主要有客户端分片、代理模式和Cluster模式,其中,Cluster模式是Redis官方推荐的实现方案,它具有高可用性、高性能和自动分片等优点
    2024-12-12
  • 解决Redis连接无法正常释放的问题

    解决Redis连接无法正常释放的问题

    这篇文章主要介绍了解决Redis连接无法正常释放的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Redis 命令的详解及简单实例

    Redis 命令的详解及简单实例

    这篇文章主要介绍了Redis 命令的详解及简单实例的相关资料,这里提供基础语法及使用实例,需要的朋友可以参考下
    2017-08-08
  • redis开启过期监听的实现示例

    redis开启过期监听的实现示例

    在Java项目中使用Redis的过期监听功能来实现订单未付款到期自动取消,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-11-11
  • Redis删除过期key策略详解

    Redis删除过期key策略详解

    Redis是一款高性能的开源内存数据库,广泛应用于缓存、消息队列、实时分析等场景,在Redis中,我们经常需要删除过期的key,以释放内存空间并保持数据的有效性,本文将为您详细介绍Redis的过期key删除策略,帮助您更好地管理和优化Redis数据库
    2023-10-10
  • Redis实战之Redis实现异步秒杀优化详解

    Redis实战之Redis实现异步秒杀优化详解

    这篇文章主要给大家介绍了Redis实战之Redis实现异步秒杀优化方法,文章通过图片和代码介绍的非常详细,对大家的学习或工作有一定的帮助,感兴趣的同学可以自己动手试一下
    2023-09-09

最新评论