Springboot使用redis实现接口Api限流的实例

时间:2021-09-29 16:17:20

前言

Springboot使用redis实现接口Api限流的实例

该篇介绍的内容如题,就是利用redis实现接口的限流(  某时间范围内 最大的访问次数 ) 。

正文 

惯例,先看下我们的实战目录结构:

Springboot使用redis实现接口Api限流的实例

首先是pom.xml 核心依赖:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--用于redis数据库连接-->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>
<!--用于redis lettuce 连接池pool使用-->
<dependency>
    <groupid>org.apache.commons</groupid>
    <artifactid>commons-pool2</artifactid>
</dependency>
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>

然后是application.yml里面的redis接入配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spring:
  redis:
    lettuce:
      pool:
        #连接池最大连接数 使用负值代表无限制 默认为8
        max-active: 10
        #最大空闲连接 默认8
        max-idle: 10
        #最小空闲连接 默认0
        min-idle: 1
    host: 127.0.0.1
    password: 123456
    port: 6379
    database: 0
    timeout: 2000ms
server:
  port: 8710

redis的配置类, redisconfig.java:

ps:可以看到日期是18年的,因为这些redis的整合教程,在这个系列里面一共有快10篇,不了解的看客如果感兴趣可以去看一看。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import com.fasterxml.jackson.annotation.jsonautodetect;
import com.fasterxml.jackson.annotation.propertyaccessor;
import com.fasterxml.jackson.databind.objectmapper;
import org.springframework.cache.cachemanager;
import org.springframework.cache.annotation.enablecaching;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.cache.rediscacheconfiguration;
import org.springframework.data.redis.cache.rediscachemanager;
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.serializer.jackson2jsonredisserializer;
import org.springframework.data.redis.serializer.redisserializationcontext;
import org.springframework.data.redis.serializer.stringredisserializer;
 
import static org.springframework.data.redis.cache.rediscacheconfiguration.defaultcacheconfig;
 
/**
 * @author: jcccc
 * @createtime: 2018-09-11
 * @description:
 */
@configuration
@enablecaching
public class redisconfig {
    @bean
    public cachemanager cachemanager(redisconnectionfactory connectionfactory) {
        rediscacheconfiguration cacheconfiguration =
                defaultcacheconfig()
                        .disablecachingnullvalues()
                        .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(new jackson2jsonredisserializer(object.class)));
        return rediscachemanager.builder(connectionfactory).cachedefaults(cacheconfiguration).build();
    }
 
 
    @bean
    public redistemplate<string, object> redistemplate(redisconnectionfactory factory) {
        redistemplate<string, object> redistemplate = new redistemplate<>();
        redistemplate.setconnectionfactory(factory);
        jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
        objectmapper om = new objectmapper();
        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
        om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
        jackson2jsonredisserializer.setobjectmapper(om);
        //序列化设置 ,这样为了存储操作对象时正常显示的数据,也能正常存储和获取
        redistemplate.setkeyserializer(new stringredisserializer());
        redistemplate.setvalueserializer(jackson2jsonredisserializer);
        redistemplate.sethashkeyserializer(new stringredisserializer());
        redistemplate.sethashvalueserializer(jackson2jsonredisserializer);
        return redistemplate;
    }
    @bean
    public stringredistemplate stringredistemplate(redisconnectionfactory factory) {
        stringredistemplate stringredistemplate = new stringredistemplate();
        stringredistemplate.setconnectionfactory(factory);
        return stringredistemplate;
    }
}

自定义注解:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.lang.annotation.*;
 
/**
 * @author jcccc
 * @description
 * @date 2021/7/23 11:46
 */
@inherited
@documented
@target({elementtype.field, elementtype.type, elementtype.method})
@retention(retentionpolicy.runtime)
public @interface requestlimit {
 
    /**
     * 时间内  秒为单位
     */
    int second() default 10;
 
    /**
     *  允许访问次数
     */
    int maxcount() default 5;
 
 
    //默认效果 : 10秒内 对于使用该注解的接口,只能总请求访问数 不能大于 5次
 
}

接下来是拦截器 requestlimitinterceptor.java:

拦截接口的方式 是通过 ip地址+接口url ,做时间内的访问计数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import com.elegant.testdemo.annotation.requestlimit;
import com.elegant.testdemo.utils.iputil;
import com.fasterxml.jackson.databind.objectmapper;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
import org.springframework.web.method.handlermethod;
import org.springframework.web.servlet.handlerinterceptor;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.util.concurrent.timeunit;
 
/**
 * @author jcccc
 * @description
 * @date 2021/7/23 11:49
 */
 
@component
public class requestlimitinterceptor implements handlerinterceptor {
    private final logger log = loggerfactory.getlogger(this.getclass());
 
    @autowired
    private redistemplate<string, object> redistemplate;
 
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        try {
            if (handler instanceof handlermethod) {
                handlermethod handlermethod = (handlermethod) handler;
                // 获取requestlimit注解
                requestlimit requestlimit = handlermethod.getmethodannotation(requestlimit.class);
                if (null==requestlimit) {
                    return true;
                }
                //限制的时间范围
                int seconds = requestlimit.second();
                //时间内的 最大次数
                int maxcount = requestlimit.maxcount();
                string ipaddr = iputil.getipaddr(request);
                // 存储key
                string key =  ipaddr+":"+request.getcontextpath() + ":" + request.getservletpath();
                // 已经访问的次数
                integer count = (integer) redistemplate.opsforvalue().get(key);
                log.info("检测到目前ip对接口={}已经访问的次数", request.getservletpath() , count);
                if (null == count || -1 == count) {
                    redistemplate.opsforvalue().set(key, 1, seconds, timeunit.seconds);
                    return true;
                }
                if (count < maxcount) {
                    redistemplate.opsforvalue().increment(key);
                    return true;
                }
                log.warn("请求过于频繁请稍后再试");
                returndata(response);
                return false;
            }
            return true;
        } catch (exception e) {
            log.warn("请求过于频繁请稍后再试");
            e.printstacktrace();
        }
        return true;
    }
 
    public void returndata(httpservletresponse response) throws ioexception {
        response.setcharacterencoding("utf-8");
        response.setcontenttype("application/json; charset=utf-8");
        objectmapper objectmapper = new objectmapper();
        //这里传提示语可以改成自己项目的返回数据封装的类
        response.getwriter().println(objectmapper.writevalueasstring("请求过于频繁请稍后再试"));
        return;
    }
 
}

接下来是 拦截器的配置 webconfig.java:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import com.elegant.testdemo.interceptor.requestlimitinterceptor;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.interceptorregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
 
/**
 * @author jcccc
 * @description
 * @date 2021/7/23 11:52
 */
 
@configuration
public class webconfig implements webmvcconfigurer {
    @autowired
    private requestlimitinterceptor requestlimitinterceptor;
 
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(requestlimitinterceptor)
 
                //拦截所有请求路径
                .addpathpatterns("/**")
                //再设置 放开哪些路径
                .excludepathpatterns("/static/**","/auth/login");
    }
 
}

最后还有两个工具类

iputil:

 

redisutil :

 

最后写个测试接口

testcontroller.java 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.elegant.testdemo.annotation.requestlimit;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
 
 
/**
 * @author jcccc
 * @description
 * @date 2021/7/23 11:55
 */
@restcontroller
public class testcontroller {
 
    @getmapping("/test")
    @requestlimit(maxcount = 3,second = 60)
    public string test() {
        return "你好,如果对你有帮助,请点赞加关注。";
    }
}

这个/test接口的注解,我们设置的是 60秒内 最大访问次数为 3次 (实际应用应该是根据具体接口做相关的次数限制。)

然后使用postman测试一下接口:

前面三次都是请求通过的:

Springboot使用redis实现接口Api限流的实例

Springboot使用redis实现接口Api限流的实例

 第四次:

Springboot使用redis实现接口Api限流的实例

到此这篇关于springboot使用redis实现接口api限流的实例的文章就介绍到这了,更多相关springboot redis接口api限流内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_35387940/article/details/119116534