1.熟悉下lua语法
2.lua安装,IDEA安装lua插件
安装Lua:
1. 参考http://www.lua.org/ftp/教程,下载5.3.5_1版本,本地安装
如果是Mac,那用brew工具直接执行brew install lua就可以顺利安装,
有关brew工具的安装可以参考https://brew.sh/网站,建议翻墙否则会很慢。
使用brew安装后的目录在/usr/local/Cellar/lua/5.3.5_1
2. 安装IDEA插件,在IDEA->Preferences面板,Plugins,
里面Browse repositories,在里面搜索lua,然后就选择同名插件lua。安装好后重启IDEA
3. 配置Lua SDK的位置: IDEA->File->Project Structure,
选择添加Lua,路径指向Lua SDK的bin文件夹,我本地的地址是:
/usr/local/Cellar/lua/5.3.5_1/bin
3.创建jar模块,作为公用组件
具体的文件及代码内容如下:
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>xxx</artifactId>
<groupId>com.xxx</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>ratelimiter-annotation</artifactId>
<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>
</project>
2.resource目录下添加lua脚本
ratelimiter.lua
-- 获取方法签名特征
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
3.src目录包结构自己定义,添加配置类
RedisConfiguration.java
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;
@Configuration
public class RedisConfiguration {
// 如果本地也配置了StringRedisTemplate,可能会产生冲突
// 可以指定@Primary,或者指定加载特定的@Qualifier
@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;
}
}
4.定义注解截切面类与具体通过redis调用lua脚本实现限流的两个类。放到创建的一个annotation包下
AccessLimiter.java
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AccessLimiter {
int limit();
String methodKey() default "";
}
AccessLimiterAspect.java
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.beans.factory.annotation.Autowired;
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;
@Slf4j
@Aspect
@Component
public class AccessLimiterAspect {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisScript<Boolean> rateLimitLua;
@Pointcut("@annotation(com.xxx.xxx.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();
Integer 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列表
limit.toString() // Lua脚本Value列表
);
if (!acquired) {
log.error("your access is blocked, key={}", key);
throw new RuntimeException("Your access is blocked");
}
}
}
至此redis+lua限流组件开发完成。下面在其他模块中使用测试。
使用步骤:
1.在需要用到的工程中引入限流组件的依赖包
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>ratelimiter-annotation</artifactId>
<version>${project.version}</version>
</dependency>
2.在需要限流的controller接口上进行限流注解即可。
// limit后的值为限流流量数限1秒1个请求
@GetMapping("test-annotation")
@com.xxx.xxx.annotation.AccessLimiter(limit = 1)
public String testAnnotation() {
return "success";
}