Spring Boot+Redis 扛住,瞬间千次重复提交

redis+token实现登录校验,前后端分离,及解跨域问题的4种方法 一、使用自定义filter实现跨域 1、客户端向服务端发送请求 2、服务端做登录验证了,并生成登路用户对应的token,保存到redis 3、响应(报错)-----跨域问题 4、解决跨域问题--------服务器端添加过滤器,设置请求头 5、重新登录正确响应 6、客户端登redis录后访问页面,需要经过拦截器验证登录状态 7、编写拦截器 二、在任意配置类,返回一个 新的 CorsFIlter Bean 三、使用注解 (局部跨域) 四、手动设置响应头(局部跨域) 阅读详情

作者:慕容千语 

来源:http://suo.im/5PaEZI

 

前言:

在实际的开发项目中,一个对外暴露的接口往往会面临,瞬间大量的重复的请求提交,如果想过滤掉重复请求造成对业务的伤害,那就需要实现幂等!

我们来解释一下幂等的概念:

任意多次执行所产生的影响均与一次执行的影响相同。按照这个含义,最终的含义就是 对数据库的影响只能是一次性的,不能重复处理。

如何保证其幂等性,通常有以下手段:

1、数据库建立唯一性索引,可以保证最终插入数据库的只有一条数据
2、token机制,每次接口请求前先获取一个token,然后再下次请求的时候在请求的header体中加上这个token,后台进行验证,如果验证通过删除token,下次请求再次判断token
3、悲观锁或者乐观锁,悲观锁可以保证每次for update的时候其他sql无法update数据(在数据库引擎是innodb的时候,select的条件必须是唯一索引,防止锁全表)
4、先查询后判断,首先通过查询数据库是否存在数据,如果存在证明已经请求过了,直接拒绝该请求,如果没有存在,就证明是第一次进来,直接放行。

redis实现自动幂等的原理图:

一、搭建redis的服务Api

1、首先是搭建redis服务器。

2、引入springboot中到的redis的stater,或者Spring封装的jedis也可以,后面主要用到的api就是它的set方法和exists方法,这里我们使用springboot的封装好的redisTemplate

 
  1. /**

  2. * redis工具类

  3. */

  4. @Component

  5. public class RedisService {

  6.    @Autowired

  7.    private RedisTemplate redisTemplate;

  8.    /**

  9.     * 写入缓存

  10.     * @param key

  11.     * @param value

  12.     * @return

  13.     */

  14.    public boolean set(final String key, Object value) {

  15.        boolean result = false;

  16.        try {

  17.            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

  18.            operations.set(key, value);

  19.            result = true;

  20.        } catch (Exception e) {

  21.            e.printStackTrace();

  22.        }

  23.        return result;

  24.    }

  25.    /**

  26.     * 写入缓存设置时效时间

  27.     * @param key

  28.     * @param value

  29.     * @return

  30.     */

  31.    public boolean setEx(final String key, Object value, Long expireTime) {

  32.        boolean result = false;

  33.        try {

  34.            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

  35.            operations.set(key, value);

  36.            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);

  37.            result = true;

  38.        } catch (Exception e) {

  39.            e.printStackTrace();

  40.        }

  41.        return result;

  42.    }

  43.    /**

  44.     * 判断缓存中是否有对应的value

  45.     * @param key

  46.     * @return

  47.     */

  48.    public boolean exists(final String key) {

  49.        return redisTemplate.hasKey(key);

  50.    }

  51.    /**

  52.     * 读取缓存

  53.    

Redis如何做token缓存 除了缓存token,我们还可以使用Redis做更多的事情,比如计数器、排行榜等。由于Redis是一个内存数据库,它的读取速度非常快,因此可以用于缓存高频读取的数据。而且,Redis是一个开源的数据库,它可以轻松地分布式部署,支持数据备份和恢复,还可以提供多种数据结构以适应不同的业务需求。此外,我们还可以使用Redis实现缓存穿透、缓存雪崩、缓存击穿等问题的解决方案。在实际开发中,我们要考虑到缓存的安全性、一致性等问题,以保证应用的性能和可靠性。最后,附上本文的完整代码,供读者参考。 阅读详情

相关推荐

保证接口幂等性(token机制)

Token机制是实现接口幂等性的一种常见策略,本文实现了token机制的代码

stu_kk的博客 2780

小米手机免登录开启USB安装与调试(MIUI 9-11实测,已Root可用)

本文详细介绍了小米手机免登录开启USB安装与调试的底层方案,适用于已Root的MIUI 9-11版本设备。通过修改系统配置、禁用MIUI安装器验证和强制开启USB调试等步骤,帮助开发者绕过账号限制,实现快速调试。文章包含不同MIUI版本的兼容性处理和常见问题解决方法,实测有效。

weixin_33675507的博客 303

WinServer 2012 R2 搭建 AD 单域多站点 及 DNS各站点的子网掩码排序调整

WinServer 2012 R2 搭建 AD 单域多站点 及 DNS各站点的子网掩码排序调整

一直被模仿,从未被超越 5543

长安车机破解后能干啥?分享我的UNI-K车机安装第三方应用与优化体验实录

本文详细记录了长安UNI-K车机破解后的实用玩法与深度优化指南,包括安装第三方应用、导航体验升级、影音系统改造及系统美化等。通过工具箱和升级技巧,车主可以大幅提升用车体验,解锁更多隐藏功能。

weixin_33217202的博客 422

PHP版本对接支付宝支付接口 电脑网站 详细介绍 沙箱环境 超简单易懂

PHP版本对接支付宝支付接口 其实理顺了思路后,按照我接下来的步骤来,真的超级简单啊,为啥有那么多的朋友们折腾了那么久呢,嘿嘿,跟我走吧~ 我是昨天晚上洗完澡之后,大概八九点,才开始正式开工尝试去这一工程的,我去支付宝的蚂蚁金服开放平台里把各个知识点和文档大概都看了一遍,大致弄明白了要怎么操作了,建议大家看看电脑网站开发文档,忙到了夜里十二点左右,成功地用支付宝给的Demo完成了付款操...

爱玲姐姐的博客 1万+

别再手动上传了!用宝塔面板的‘Let‘s Encrypt’免费SSL证书,3分钟自动续期

本文详细介绍了如何利用宝塔面板的‘Let‘s Encrypt’功能实现SSL证书的自动申请和续期,3分钟完成配置即可永久免费使用。通过对比不同SSL证书方案,突出Let's Encrypt的免费、自动续期和高安全性优势,特别适合个人博客和中小企业官网。

weixin_30415113的博客 154

PyTorch深度学习实战(39)——少样本学习(Few-shot Learning)

小样本学习 (Few-shot Learning) 旨在解决在训练集中只有很少样本的情况下进行分类和推理的问题。在小样本学习中,我们希望通过利用已有的少量样本和先验知识来进行泛化,以便在面对新的、未见过的类别时能够做出准确的预测。这就要求模型能够从有限的训练样本中提取出有用的信息,并能够将这些信息应用到新类别的样本中去。在本节中,将介绍孪生、原型和关系网络的原理,并使用 PyTorch 实现孪生网络。

盼小辉丶的博客 1万+

YOLOv11改进策略【卷积层】| ICCV-2023 LSK大核选择模块 包含二次独家创新

LSK module是。

Limiiiing的博客 1398

人像抠图 + OpenGL ES 还能这样玩?没想到吧(附带源码)

OpenGL ES 利用抠图算法实现人像留色。

字节流动 3万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

深度学习工具包 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")

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

上一篇: 10 大黑客专用的 Linux 操作系统
下一篇: 主流WEB漏洞扫描器种类及其指纹特征分析
K'illCode
博客等级 码龄9年 763粉丝 838原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值