接口限流
在一个高并发系统中对流量的把控是非常重要的,当巨大的流量直接请求到我们的服务器上没多久就可能造成接口不可用,不处理的话甚至会造成整个应用不可用。为了避免这种情况的发生我们就需要在请求接口时对接口进行限流的操作。
怎么做?
基于springboot而言,我们想到的是通过redis的自加:incr来实现。我们可以通过用户的唯一标识来设计成redis的key,值为单位时间内用户的请求次数。
一、准备工作
创建spring boot 工程,引入 web 和 redis 依赖,同时考虑到接口限流一般是通过注解来标记,而注解是通过 aop 来解析的,所以我们还需要加上 aop 的依赖:
<!-- 需要的依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-aop</artifactid>
</dependency>提前准备好一个redis示例,并在项目中进行配置。
#具体配置以实际为主这里只是演示 spring: redis: host: localhost port: 6379 password: 123
二、创建限流注解
限流我们一般分为两种情况:
1、针对某一个接口单位时间内指定允许访问次数,例如:a接口1分钟内允许访问100次;
2、针对ip地址进行限流,例如:ip地址a可以在1分钟内访问接口50次;
针对这两种情况我们定义一个枚举类:
public enum limittype {
/**
* 默认策略
*/
default,
/**
* 根据ip进行限流
*/
ip
}接下来定义限流注解:
@documented
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface ratelimiter {
/**
* 限流key
*/
string key() default "rate_limit:";
/**
* 限流时间,单位秒
*/
int time() default 60;
/**
* 限流次数
*/
int count() default 50;
/**
* 限流类型
*/
limittype limittype() default limittype.default;
}第一个参数 key 是一个前缀,实际使用过程中是这个前缀加上接口方法的完整路径共同来组成一个 key 来存到redis中。使用时在需要进行限流的接口中加上注解并配置详细的参数即可。
三、定制redistemplate
在实际使用过程中我们通常是通过redistemplate来操作redis的,所以这里就需要定制我们需要的redistemplate,默认的redistemplate中是有一下小问题的,就是直接使用jdkserializationredisserializer这个工具进行序列化时存放到redis中的key和value是会多一些前缀的,这样就会导致我们在读取数据时可能会出现错误。
修改 redistemplate 序列化方案,代码如下:
@bean
public redistemplate<string, object> redistemplate(redisconnectionfactory factory) {
redistemplate<string, object> template = new redistemplate<>();
// 配置连接工厂
template.setconnectionfactory(factory);
//使用jackson2jsonredisserializer来序列化和反序列化redis的value值(默认使用jdk的序列化方式)
jackson2jsonredisserializer<object> jacksonseial = new jackson2jsonredisserializer<>(object.class);
objectmapper om = new objectmapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,any是都有包括private和public
om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如string,integer等会跑出异常
om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
jacksonseial.setobjectmapper(om);
// 值采用json序列化
template.setvalueserializer(jacksonseial);
//使用stringredisserializer来序列化和反序列化redis的key值
template.setkeyserializer(new stringredisserializer());
// 设置hash key 和value序列化模式
template.sethashkeyserializer(new stringredisserializer());
template.sethashvalueserializer(jacksonseial);
template.afterpropertiesset();
return template;
}四、开发lua脚本
我们在java 代码中将 lua 脚本定义好,然后发送到 redis 服务端去执行。我们在 resources 目录下新建 lua 文件夹专门用来存放 lua 脚本,脚本内容如下:
local key = keys[1]
local count = tonumber(argv[1])
local time = tonumber(argv[2])
local current = redis.call('get', key)
if current and tonumber(current) > count then
return tonumber(current)
end
current = redis.call('incr', key)
if tonumber(current) == 1 then
redis.call('expire', key, time)
end
return tonumber(current)keys 和 argv 都是一会调用时候传进来的参数,tonumber 就是把字符串转为数字,redis.call 就是执行具体的 redis 指令。具体的流程:
- 首先获取到传进来的 key 以及 限流的 count 和时间 time。
- 通过 get 获取到这个 key 对应的值,这个值就是当前时间段内这个接口访问了多少次。
- 如果是第一次访问,此时拿到的结果为 nil,否则拿到的结果应该是一个数字,所以接下来就判断,如果拿到的结果是一个数字,并且这个数字还大于 count,那就说明已经超过流量限制了,那么直接返回查询的结果即可。
- 如果拿到的结果为 nil,说明是第一次访问,此时就给当前 key 自增 1,然后设置一个过期时间。
- 最后把自增 1 后的值返回就可以了。
接下来写一个bean来加载这个脚本:
@bean
public defaultredisscript<long> limitscript() {
defaultredisscript<long> redisscript = new defaultredisscript<>();
redisscript.setscriptsource(new resourcescriptsource(new classpathresource("lua/limit.lua")));
redisscript.setresulttype(long.class);
return redisscript;
}五、解析注解
自定义切面解析注解:
@slf4j
@aspect
@component
public class ratelimiteraspect {
private final redistemplate redistemplate;
private final redisscript<long> limitscript;
public ratelimiteraspect(redistemplate redistemplate, redisscript<long> limitscript) {
this.redistemplate = redistemplate;
this.limitscript = limitscript;
}
@around("@annotation(com.example.demo.annotation.ratelimiter)")
public object dobefore(proceedingjoinpoint joinpoint) throws throwable{
methodsignature methodsignature = (methodsignature) joinpoint.getsignature();
ratelimiter ratelimiter = methodsignature.getmethod().getannotation(ratelimiter.class);
//判断该方法是否存在限流的注解
if (null != ratelimiter){
//获得注解中的配置信息
int count = ratelimiter.count();
int time = ratelimiter.time();
string key = ratelimiter.key();
//调用getcombinekey()获得存入redis中的key key -> 注解中配置的key前缀-ip地址-方法路径-方法名
string combinekey = getcombinekey(ratelimiter, methodsignature);
log.info("combinekey->,{}",combinekey);
//将combinekey放入集合
list<object> keys = collections.singletonlist(combinekey);
log.info("keys->",keys);
try {
//执行lua脚本获得返回值
long number = (long) redistemplate.execute(limitscript, keys, count, time);
//如果返回null或者返回次数大于配置次数,则限制访问
if (number==null || number.intvalue() > count) {
throw new serviceexception("访问过于频繁,请稍候再试");
}
log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intvalue(), combinekey);
} catch (serviceexception e) {
throw e;
} catch (exception e) {
throw new runtimeexception("服务器限流异常,请稍候再试");
}
}
return joinpoint.proceed();
}
/**
* gets combine key.
*
* @param ratelimiter the rate limiter
* @param signature the signature
* @return the combine key
*/
public string getcombinekey(ratelimiter ratelimiter, methodsignature signature) {
stringbuilder stringbuffer = new stringbuilder(ratelimiter.key());
if (ratelimiter.limittype() == limittype.ip) {
stringbuffer.append(requestutil.getipaddr(((servletrequestattributes) requestcontextholder.currentrequestattributes()).getrequest())).append("-");
}
method method = signature.getmethod();
class<?> targetclass = method.getdeclaringclass();
stringbuffer.append(targetclass.getname()).append("-").append(method.getname());
return stringbuffer.tostring();
}
}六、自定义异常处理
由于访问次数达到限制时是抛异常出来,所以我们还需要写一个全局异常捕获:
/**
* 自定义serviceexception
*/
public class serviceexception extends exception{
public serviceexception(){
super();
}
public serviceexception(string msg){
super(msg);
}
}
/**
* 异常捕获处理
*/
@restcontrolleradvice
public class globalexceptionadvice {
@exceptionhandler(serviceexception.class)
public result<object> serviceexception(serviceexception e) {
//result.failure()是我们在些项目是自定义的统一返回
return result.failure(e.getmessage());
}
}七、测试结果
测试代码:
@getmapping("/strategy")
@ratelimiter(time = 3,count = 1,limittype = limittype.ip)
public string strategytest(){
return "test";
}当访问次数大于配置的限制时限制接口调用 ↓

正常结果 ↓

到此这篇关于使用redis完成接口限流的过程的文章就介绍到这了,更多相关redis接口限流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论