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

相关文章

  • Redis报错:Could not create server TCP listening socket 127.0.0.1:6379: bind:解决方法

    Redis报错:Could not create server TCP 

    这篇文章主要介绍了Redis报错:Could not create server TCP listening socket 127.0.0.1:6379: bind:解决方法,是安装与启动Redis过程中比较常见的问题,需要的朋友可以参考下
    2023-06-06
  • Redis数据结构之链表与字典的使用

    Redis数据结构之链表与字典的使用

    这篇文章主要介绍了Redis数据结构之链表与字典的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • Redis总结笔记(一):安装和常用命令

    Redis总结笔记(一):安装和常用命令

    这篇文章主要介绍了Redis总结笔记(一):安装和常用命令,本文着重总结了常用命令,如对value操作的命令、对String操作的命令、对List操作的命令、对Set操作的命令等,需要的朋友可以参考下
    2015-01-01
  • 使用Redis有序集合实现IP归属地查询详解

    使用Redis有序集合实现IP归属地查询详解

    这篇文章主要介绍了使用Redis有序集合实现IP归属地查询,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • Redis报错UnrecognizedPropertyException: Unrecognized field问题

    Redis报错UnrecognizedPropertyException: Unrecognized 

    在使用SpringBoot访问Redis时,报错提示识别不了属性headPart,经过排查,发现并非Serializable或getset方法问题,而是存在一个方法getHeadPart,但无headPart属性,解决方案是将getHeadPart改为makeHeadPart
    2024-10-10
  • redis不能访问本机真实ip地址的解决方案

    redis不能访问本机真实ip地址的解决方案

    这篇文章主要介绍了redis不能访问本机真实ip地址的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • k8s部署redis cluster集群的实现

    k8s部署redis cluster集群的实现

    在Kubernetes中部署Redis集群面临挑战,因为每个Redis实例都依赖于一个配置文件,该文件可以跟踪其他集群实例及其角色。需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • Redis集群部署的过程详解

    Redis集群部署的过程详解

    Redis集群是Redis官方推出的分布式解决方案,它允许将数据分布在多个Redis节点中,从而提高Redis的性能和可扩展性,本文给大家介绍了Redis集群部署的过程步骤,需要的朋友可以参考下
    2024-06-06
  • redis如何查看锁是否存在

    redis如何查看锁是否存在

    文章介绍了两种方法来检查Redis锁的状态:使用GET命令查看锁的值和使用EXISTS命令检查锁的存在性,这两种方法都是通过连接到Redis服务器并执行相应的命令来实现的,GET命令用于获取指定键的值,而EXISTS命令用于检查指定键是否存在
    2025-01-01
  • 详解用Redis实现Session功能

    详解用Redis实现Session功能

    本篇文章主要介绍了用Redis实现Session功能,具有一定的参考价值,小编觉得挺不错的,现在分享给大家,也给大家做个参考。
    2016-12-12

最新评论