脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 基于注解实现 SpringBoot 接口防刷的方法

基于注解实现 SpringBoot 接口防刷的方法

2021-09-13 00:04杀人偿命百岁 Python

这篇文章主要介绍了基于注解实现 SpringBoot 接口防刷的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

该示例项目通过自定义注解,实现接口访问次数控制,从而实现接口防刷功能,项目结构如下:

基于注解实现 SpringBoot 接口防刷的方法

一、编写注解类 accesslimit

?
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
package cn.mygweb.annotation;
 
import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;
 
/**
 * 访问控制注解(实现接口防刷功能)
 */
@retention(retentionpolicy.runtime)
@target(elementtype.method)
public @interface accesslimit {
  /**
   * 限制周期(单位为秒)
   *
   * @return
   */
  int seconds();
 
  /**
   * 规定周期内限制次数
   *
   * @return
   */
  int maxcount();
 
  /**
   * 是否需要登录
   *
   * @return
   */
  boolean needlogin() default false;
}

二、在interceptor拦截器中实现拦截逻辑

?
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package cn.mygweb.interceptor;
 
import cn.mygweb.annotation.accesslimit;
import cn.mygweb.entity.result;
import cn.mygweb.entity.statuscode;
import com.alibaba.fastjson.json;
import org.springframework.stereotype.component;
import org.springframework.web.method.handlermethod;
import org.springframework.web.servlet.handler.handlerinterceptoradapter;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.outputstream;
import java.util.hashmap;
import java.util.map;
 
/**
 * 访问控制拦截器
 */
@component
public class accesslimitinterceptor extends handlerinterceptoradapter {
 
  //模拟数据存储,实际业务中可以自定义实现方式
  private static map<string, accessinfo> accessinfomap = new hashmap<>();
 
  @override
  public boolean prehandle(httpservletrequest request, httpservletresponse response,
               object handler) throws exception {
    //判断请求是否属于方法的请求
    if (handler instanceof handlermethod) {
      handlermethod hm = (handlermethod) handler;
 
      //获取方法中的注解,看是否有该注解
      accesslimit accesslimit = hm.getmethodannotation(accesslimit.class);
      if (accesslimit == null) {
        return true;
      }
      int seconds = accesslimit.seconds();
      int maxcount = accesslimit.maxcount();
      boolean needlogin = accesslimit.needlogin();
      string key = request.getrequesturi();
      //如果需要登录
      if (needlogin) {
        //获取登录的session进行判断
        //……
        key += " " + "usera";//这里假设用户是usera,实际项目中可以改为userid
      }
 
      //模拟从redis中获取数据
      accessinfo accessinfo = accessinfomap.get(key);
      if (accessinfo == null) {
        //第一次访问
        accessinfo = new accessinfo();
        accessinfo.setfirstvisittimestamp(system.currenttimemillis());
        accessinfo.setaccesscount(1);
        accessinfomap.put(key, accessinfo);
      } else if (accessinfo.getaccesscount() < maxcount) {
        //访问次数加1
        accessinfo.setaccesscount(accessinfo.getaccesscount() + 1);
        accessinfomap.put(key, accessinfo);
      } else {
        //超出访问次数,判断时间是否超出设定时间
        if ((system.currenttimemillis() - accessinfo.getfirstvisittimestamp()) <= seconds * 1000) {
          //如果还在设定时间内,则为不合法请求,返回错误信息
          render(response, "达到访问限制次数,请稍后重试!");
          return false;
        } else {
          //如果超出设定时间,则为合理的请求,将之前的请求清空,重新计数
          accessinfo.setfirstvisittimestamp(system.currenttimemillis());
          accessinfo.setaccesscount(1);
          accessinfomap.put(key, accessinfo);
        }
      }
    }
    return true;
  }
 
  /**
   * 向页面发送消息
   *
   * @param response
   * @param msg
   * @throws exception
   */
  private void render(httpservletresponse response, string msg) throws exception {
    response.setcontenttype("application/json;charset=utf-8");
    outputstream out = response.getoutputstream();
    string str = json.tojsonstring(new result(true, statuscode.accesserror, msg));
    out.write(str.getbytes("utf-8"));
    out.flush();
    out.close();
  }
 
  /**
   * 封装的访问信息对象
   */
  class accessinfo {
 
    /**
     * 一个计数周期内第一次访问的时间戳
     */
    private long firstvisittimestamp;
    /**
     * 访问次数统计
     */
    private int accesscount;
 
    public long getfirstvisittimestamp() {
      return firstvisittimestamp;
    }
 
    public void setfirstvisittimestamp(long firstvisittimestamp) {
      this.firstvisittimestamp = firstvisittimestamp;
    }
 
    public int getaccesscount() {
      return accesscount;
    }
 
    public void setaccesscount(int accesscount) {
      this.accesscount = accesscount;
    }
 
    @override
    public string tostring() {
      return "accessinfo{" +
          "firstvisittimestamp=" + firstvisittimestamp +
          ", accesscount=" + accesscount +
          '}';
    }
  }
}

三、把interceptor注册到springboot中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.mygweb.config;
 
import cn.mygweb.interceptor.accesslimitinterceptor;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.interceptorregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
 
/**
 * 拦截器注册配置
 */
@configuration
public class webconfig implements webmvcconfigurer {
 
  @override
  public void addinterceptors(interceptorregistry registry) {
    //注册拦截器
    registry.addinterceptor(new accesslimitinterceptor());
  }
}

四、在controller中加入注解实现接口防刷

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package cn.mygweb.controller;
 
import cn.mygweb.annotation.accesslimit;
import cn.mygweb.entity.result;
import cn.mygweb.entity.statuscode;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
 
@restcontroller
@requestmapping("/access")
public class accesscontroller {
 
  @accesslimit(seconds = 5, maxcount = 2)//访问控制,5秒内只能访问2次
  @getmapping
  public result access() {
    return new result(true, statuscode.ok, "访问成功!");
  }
 
}

五、测试访问

基于注解实现 SpringBoot 接口防刷的方法

附:statuscode.java、result.java、application.yml

statuscode类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package cn.mygweb.entity;
 
/**
 * 返回状态码
 */
public class statuscode {
  public static final int ok = 20000;//成功
  public static final int error = 20001;//失败
  public static final int loginerror = 20002;//用户名或密码错误
  public static final int accesserror = 20003;//权限不足
  public static final int remoteerror = 20004;//远程调用失败
  public static final int reperror = 20005;//重复操作
  public static final int notfounderror = 20006;//没有对应的抢购数据
}

result类:

?
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
package cn.mygweb.entity;
 
import java.io.serializable;
 
/**
 * 响应结果
 */
public class result<t> implements serializable {
  private boolean flag;//是否成功
  private integer code;//返回码
  private string message;//返回消息
  private t data;//返回数据
 
  public result(boolean flag, integer code, string message, object data) {
    this.flag = flag;
    this.code = code;
    this.message = message;
    this.data = (t) data;
  }
 
  public result(boolean flag, integer code, string message) {
    this.flag = flag;
    this.code = code;
    this.message = message;
  }
 
  public result() {
    this.flag = true;
    this.code = statuscode.ok;
    this.message = "操作成功!";
  }
 
  public boolean isflag() {
    return flag;
  }
 
  public void setflag(boolean flag) {
    this.flag = flag;
  }
 
  public integer getcode() {
    return code;
  }
 
  public void setcode(integer code) {
    this.code = code;
  }
 
  public string getmessage() {
    return message;
  }
 
  public void setmessage(string message) {
    this.message = message;
  }
 
  public t getdata() {
    return data;
  }
 
  public void setdata(t data) {
    this.data = data;
  }
}

applications.yml:

?
1
2
server:
 port: 8080

到此这篇关于基于注解实现 springboot 接口防刷的方法的文章就介绍到这了,更多相关springboot 接口防刷内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/g1246975590/article/details/114242386

延伸 · 阅读

精彩推荐