Springboot项目的接口防刷(实例)

置顶必读(1) | 2026最新首发,全网最全 Spring Boot 学习宝典(附思维导图) 从0到1以知识点+实例+项目的教学模式对SpringBoot框架由浅入深进行学习,快来跟bug菌一起学习吧。 阅读详情

来源:https://urlify.cn/ERf6Rr

说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考。

技术要点:springboot的基本知识,redis基本操作,

首先是写一个注解类:

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author yhq
 * @date 2018/9/10 15:52
 */

@Retention(RUNTIME)
@Target(METHOD)
public @interface AccessLimit {

    int seconds();
    int maxCount();
    boolean needLogin()default true;
}

接着就是在Interceptor拦截器中实现:

import com.alibaba.fastjson.JSON;
import com.example.demo.action.AccessLimit;
import com.example.demo.redis.RedisService;
import com.example.demo.result.CodeMsg;
import com.example.demo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @author yhq
 * @date 2018/9/10 16:05
 */


@Component
public class FangshuaInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisService redisService;

    @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 login = accessLimit.needLogin();
            String key = request.getRequestURI();
            //如果需要登录
            if(login){
                //获取登录的session进行判断
                //.....
                key+=""+"1";  //这里假设用户是1,项目中是动态获取的userId
            }

            //从redis中获取用户访问的次数
            AccessKey ak = AccessKey.withExpire(seconds);
            Integer count = redisService.get(ak,key,Integer.class);
            if(count == null){
                //第一次访问
                redisService.set(ak,key,1);
            }else if(count < maxCount){
                //加1
                redisService.incr(ak,key);
            }else{
                //超出访问次数
                render(response,CodeMsg.ACCESS_LIMIT_REACHED); //这里的CodeMsg是一个返回参数
                return false;
            }
        }

        return true;

    }
    private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}

再把Interceptor注册到springboot中

import com.example.demo.ExceptionHander.FangshuaInterceptor;
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.WebMvcConfigurerAdapter;

/**
 * @author yhq
 * @date 2018/9/10 15:58
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private FangshuaInterceptor interceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor);
    }
}

接着在Controller中加入注解

import com.example.demo.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author yhq
 * @date 2018/9/10 15:49
 */

@Controller
public class FangshuaController {

    @AccessLimit(seconds=5, maxCount=5, needLogin=true)
    @RequestMapping("/fangshua")
    @ResponseBody
    public Result<String> fangshua(){


        return Result.success("请求成功");

    }

本文有参考其他视频的教学,希望可以帮助更多热爱it行业的人。

(完)

(java思维导图)

长按关注,每天java一下,成就架构师

我就知道你在看!

SpringBoot学习路线总结(附思维导图) ???? Java基础教程系列:Java基础教程系列 ???? Java学习路线配套文章:搬砖工逆袭Java架构师 ???? Java经典面试题大全:10万字208道Java经典面试题总结(附答案) ???? 简介:Java领域优质创作者????、CSDN哪吒公众号作者✌ 、Java架构师奋斗者???? ???? 扫描主页左侧二维码,加入群聊,一起学习、一起进步 ???? 欢迎点赞 ???? 收藏 ⭐留言 ???? 立志存高远,笃行践初心 三更灯火五更鸡,正是男儿读书时。 黑发不知勤学早, 阅读详情

相关推荐

spring-boot思维导图完整知识点脑图教程

这里包含了springboot的创建,参数,配置,数据库集成,部署,拦截器等开发中常用的信息。如有错漏更正欢迎来信307793969@qq.com

接口如何防止被刷,教你有效的8种方法

现在越来越多的应用程序和服务都提供了API接口,使得开发人员可以方便地与这些应用程序和服务进行交互。但是,由于API接口是公开的,因此很容易被黑客利用,对系统造成损害。为了确保API接口的安全性,我们需要采取一些措施,例如使用签名机制和限流机制来增强接口的安全性。在本文中,我们将介绍如何使用PHP实现这些措施,并防止API接口被恶意刷。

m0_66326520的博客 4491

圆极化天线特性测试

3、将测试数据代入方向图计算程序,得到圆极化天线的H面的左旋圆极化分量的方向图和右旋圆极化分量的方向图,其中幅度较大的是主极化。1、固定好待测圆极化天线,打开方向图LABVIEW测试程序,设定测试起始频率,测量待测天线的S21的幅度P1。% title('左旋圆极化方向图','FontSize',15,'Color','b');% title('右旋圆极化方向图','FontSize',15,'Color','b');title('天线的轴比','FontSize',15,'Color','b');

Symean的博客 3374

接口安全----接口防刷

接口安全之接口防刷实现,超过十次则拦截,一分钟后恢复

weixin_51764982的博客 6649

华中科技大学 计算机组成原理 educoder Logisim平台 计算机数据表示实验

本文主要是对 计算机数据表示实验的笔记和相关Logisim平台的图,供大家学习交流使用。 需要源文件或者源代码,可以留言评论! 目录实验目的第1关:汉字国标码转区位码实验第2关:汉字机内码获取实验第3关:偶校验编码设计第4关:偶校验解码电路设计第5关:16位海明编码电路设计第6关:16位海明解码电路设计第7关:海明编码流水传输实验第8关:16位CRC并行编解码电路设计第9关:CRC编码流水传输实验实验结果: 实验目的 本实训将帮助同学们巩固对计算机中数据表示方法的理解,要求能设计汉字国标码与区位码之间的转换

weixin_48383580的博客 2万+

基于遗传算法优化BP神经网络的彩票预测模型研究

随着彩票行业的快速发展,如何提高彩票预测的准确性已成为一个热点问题。本文提出了一种基于遗传算法优化反向传播(BP)神经网络的彩票预测模型。遗传算法作为一种全局优化算法,可以有效地避免传统BP神经网络中的局部最优问题,提升预测精度。实验结果表明,结合遗传算法优化的BP神经网络模型在彩票数据预测中表现出较高的准确性和较强的泛化能力,为彩票预测提供了新的思路与技术手段。BP神经网络(Backpropagation Neural Network)是一种常见的前馈神经网络,通过反向传播算法训练网络中的权重与偏置。

Sapphire521的博客 1207

如厕神器,阿里大神手打的Spring全家桶脑图(spring+MVC+Boot+Cloud)

Spring很像银行,它不能直接创造物质财富,但是一切资源都要通过它进行流通,它能控制经济发展的走向,回到程序的世界,Spring之所以能够衍生家族系列,可见它的流行程度和使用程度,由此可见学习Spring框架是非常重要的。

老男孩的架构路 1418

delphi fmx android 自动更新(一)

所以,如果是http 则,manifest.xml application 下,https无需添加。增加android:usesCleartextTraffic="true",不然无法使用http下载东西。1,REQUEST_INSTALL_PACKAGES 权限。4,WRITE_EXTERNAL_STORAGE 权限。3,READ_EXTERNAL_STORAGE 权限。一般是从http下载安装包 apk。2,INTERNET 权限。sFile为apk包路径。

全粘工程师 557

Springboot项目的接口防刷的实例

1 Springboot项目的接口防刷的实例 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考。 技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类: import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang

weixin_43677313的博客 224

基于Transformer的相似度匹配在AI原生应用中的实现

在AI原生应用(完全基于AI能力构建的应用,如ChatGPT、Notion AI)中,“理解文本之间的相似性”是核心需求:智能搜索需要找到与用户查询最匹配的文档,推荐系统需要挖掘用户兴趣与内容的关联,对话机器人需要识别用户问题的意图是否重复……本文将聚焦“基于Transformer的相似度匹配”,覆盖技术原理、代码实现、应用场景三大模块,帮助开发者掌握从理论到落地的完整链路。本文将按照“生活场景→核心概念→技术原理→代码实战→应用案例→未来趋势”的逻辑展开。

AI 原生应用开发的博客 987

C++ 小游戏程序 (共七款)

C++编程小游戏_闪耀的天狼星的博客-CSDN博客_游戏c++C++跑酷小游戏_闪耀的天狼星的博客-CSDN博客。好玩的c++编程小游戏,共六款。代码】C++跑酷小游戏。

小天狼星_布莱克 的博客 3万+

springboot项目实例_Springboot项目的接口防刷的实例

今天跟大家分享Springboot项目的接口防刷的实例的知识。1Springboot项目的接口防刷的实例说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考。技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类:import java.lang.annotation.Retention;import java.lang.annotation...

weixin_39535701的博客 87

Android 13 内置xapk安装包的方法

安装xapk 内置xapk

安卓兼职framework和app工程师的博客 230

springboot项目实例_Springboot项目的接口防刷(实例)

来源:https://urlify.cn/ERf6Rr说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考。技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类:importjava.lang.annotation.Retention;importjava.lang.annotation.Target;importstaticjava...

weixin_28918553的博客 238

使用 Python 爬虫抓取 IMDb 电影信息 - 评分、评论与基本信息抓取教程

本文介绍了如何使用 Python 爬虫技术抓取 IMDb 电影评分、评论和基本信息。我们分别展示了通过IMDb API和两种方法抓取数据,并进行了数据存储、分析与可视化。在未来,我们还可以基于这些数据开发电影推荐系统、情感分析工具等,进一步丰富电影数据的应用场景。通过这些实践,您不仅学会了如何抓取和存储数据,还可以通过这些基础来构建自己的数据分析应用,获取更丰富的电影数据。

2201_76125261的博客 605

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

springboot中接口实例化_Springboot项目的接口防刷(实例)

来源:https://urlify.cn/ERf6Rr说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考。技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类:import java.lang.annotation.Retention;import java.lang.annotation.Target;import static java.lang...

weixin_39725844的博客 184

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

java 接口防刷_Springboot项目的接口防刷(实例)

importcom.alibaba.fastjson.JSON;importcom.example.demo.action.AccessLimit;importcom.example.demo.redis.RedisService;importcom.example.demo.result.CodeMsg;importcom.example.demo.result.Result;importorg...

weixin_30114649的博客 258

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

(收藏)Springboot项目的接口防刷(实例)

首先是写一个注解类: importjava.lang.annotation.Retention; importjava.lang.annotation.Target; importstaticjava.lang.annotation.ElementType.METHOD; importstaticjava.lang.annotation.RetentionPolicy.RUNTI...

jackyrongvip的专栏 196

一个注解搞定 SpringBoot 接口防刷,还有谁不会?

点击上方好好学java,选择星标公众号 重磅资讯,干货,第一时间送达 今日推荐:分享一套基于SpringBoot和Vue的企业级中后台开源项目,这个项目有点哇塞!个人原创100W...

好好学java 401

面试官:如何设计出健壮的秒杀系统?

???? 这是一个或许对你有用的社群???? 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料:《项目实战(视频)》:从书中学,往事上“练”《互联网高频面试题》:面朝简历学习,春暖花开《架构 x 系统设计》:摧枯拉朽,掌控面试高频场景题《精进 Java 学习指南》:系统学习,互联网主流技术栈《必读 Java 源码专栏》:知其然,知其所以然????这是一个或许...

芋艿V 159

【SpringBoot】Spring Boot 如何实现接口防刷

SpringBoot接口防刷

低调做人,低调编码,神码都是浮云 3122
上一篇: 调整姿势!登顶 MacBook高效工作环境配置!
下一篇: 这么写参数校验(Validator)就不会被劝退了~
Java思维导图
博客等级 码龄10年 306粉丝 71原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址