Spring缓存注解@Cache使用

python刷B站播放量 首先,我们要知道B站播放量计算方法:不同的IP只能算一次,如果点一下就关掉,会出现播放完成度很低的情况,反而不利。 所以我们要做的是:不停换IP地址打开视频播放页,最好能看完视频。 下面是实现方法: 获取某一个网页上的所有代理IP,返回一个IP列表: def get_ip_list(url, headers): web_data = requests.get(url, headers=headers) soup = BeautifulSoup(web_data.text, 'lxml 阅读详情
 

参考资料

http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/

http://swiftlet.net/archives/774

 

缓存注解有以下三个:

@Cacheable      @CacheEvict     @CachePut

 

@Cacheable(value=”accountCache”),这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。

示例:

 

Java代码   收藏代码
  1. @Cacheable(value="accountCache")// 使用了一个缓存名叫 accountCache   
  2. public Account getAccountByName(String userName) {  
  3.      // 方法内部实现不考虑缓存逻辑,直接实现业务  
  4.      System.out.println("real query account."+userName);   
  5.      return getFromDB(userName);   
  6. }   

 

 

@CacheEvict 注释来标记要清空缓存的方法,当这个方法被调用后,即会清空缓存。注意其中一个 @CacheEvict(value=”accountCache”,key=”#account.getName()”),其中的 Key 是用来指定缓存的 key 的,这里因为我们保存的时候用的是 account 对象的 name 字段,所以这里还需要从参数 account 对象中获取 name 的值来作为 key,前面的 # 号代表这是一个 SpEL 表达式,此表达式可以遍历方法的参数对象,具体语法可以参考 Spring 的相关文档手册。

示例:

 

Java代码   收藏代码
  1. @CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存    
  2. public void updateAccount(Account account) {  
  3.      updateDB(account);   
  4. }   
  5.     
  6. @CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存  
  7. public void reload() {  
  8.      reloadAll()  
  9. }  
  10.   
  11. @Cacheable(value="accountCache",condition="#userName.length() <=4")// 缓存名叫 accountCache   
  12. public Account getAccountByName(String userName) {   
  13.  // 方法内部实现不考虑缓存逻辑,直接实现业务  
  14.  return getFromDB(userName);   
  15. }  

 

@CachePut 注释,这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。

示例:

 

Java代码   收藏代码
  1. @CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 缓存  
  2. public Account updateAccount(Account account) {   
  3.    return updateDB(account);   
  4. }   

 

@Cacheable、@CachePut、@CacheEvict 注释介绍

通过上面的例子,我们可以看到 spring cache 主要使用两个注释标签,即 @Cacheable、@CachePut 和 @CacheEvict,我们总结一下其作用和配置方法。

表 1. @Cacheable 作用和配置方法
@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@Cacheable 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
表 2. @CachePut 作用和配置方法
@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
@CachePut 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
表 3. @CacheEvict 作用和配置方法
@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
@CacheEvict 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@CachEvict(value=”mycache”) 或者 
@CachEvict(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@CachEvict(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才清空缓存 例如:
@CachEvict(value=”testcache”,
condition=”#userName.length()>2”)
allEntries 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 例如:
@CachEvict(value=”testcache”,allEntries=true)
beforeInvocation 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 例如:
@CachEvict(value=”testcache”,beforeInvocation=true)
改进的主动轮廓模型实现图像分割 主动轮廓模型的优点在于可以自适应地调整轮廓形状和位置,适用于不同形状和大小的目标分割。改进的主动轮廓模型是一种有效的图像分割方法,能够适应不同场景下的图像分割需求。改进的主动轮廓模型涉及到许多参数,如模型参数、分割参数、权值系数等,这些参数的调整也会直接影响到分割结果。本文将介绍一个改进的主动轮廓模型,该模型可以实现对图像进行有效的分割。改进的主动轮廓模型是在传统的主动轮廓模型基础上进行的改进。和传统的模型相比,改进的主动轮廓模型加入了外部力和内部力,能够更好地适应复杂场景下的图像分割。 阅读详情

相关推荐

解决Unity打包后粒子特效显示不全的问题

粒子特效在Editor下显示没有问题,但打包后出现部分粒子特效里的Mesh没有显示。

agoo_indie的博客 4386

Spring Cache的@Cacheable注解的condition属性与unless属性细节问题

Spring Cache的@Cacheable注解的condition属性与unless属性细节问题

鱼仔的博客 1716

具身智能Agent学习路线与面试指南:从ROS 2到多模态大模型实战

围绕具身智能这一前沿方向,从技术概念与原理出发,解析大模型如何赋予机器人理解、规划与执行能力,梳理从ROS 2基础、感知算法到运动控制、Sim2Real迁移的完整技术栈。结合工程实践,介绍企业级应用场景中的项目落地与面试高频考点,帮助学习者构建贯通感知-决策-控制的技能体系,抓住行业窗口期。

weixin_42624889的博客 205

@Cacheable注解关于condition和unless的问题

@Cacheable注解关于condition和unless的问题

qq_35460193的博客 1250

深入解析MAML-Pytorch实现:从理论到代码实践

本文深入解析了MAML(Model-Agnostic Meta-Learning)在Pytorch中的实现,从基础概念到代码实践全面覆盖。详细介绍了MAML的核心思想、环境搭建、网络架构设计、训练流程优化及常见问题解决方案,帮助开发者快速掌握这一元学习算法。特别针对Pytorch实现提供了优化技巧和实际应用案例,适合希望将MAML应用于快速适应新任务的开发者。

weixin_29038537的博客 385

当我们谈论Unidbg时我们在谈什么

文章目录一、前言二、使用Unidbg的工作量是什么三、补环境补的是什么3.1 运行环境缺失3.2 上下文缺失四、Unidbg 不是所有情况下最优的解决方案五、Unidbg在大多数情况下是好的方案六、Unidbg和风控无关七、尾声 一、前言 这是一篇漫谈Unidbg的文章,我对Unidbg的使用和理解都还很浅,日后会更新或修改看法,欢迎大佬指点,也期待同侪讨论。 二、使用Unidbg的工作量是什么 我们常规使用Frida + IDA的动静态分析中,工作可能是这样的 找线索→Frida Hook验证→验证成功继

lilac的博客 5797

Spring实战——缓存使用condition

一配置文件 <?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.sp...

实践求真知 626

从HCI层浅析LE Audio通话建立流程

本文分析了BLE AUDIO通话协议建立的全过程。当手机来电时,系统会通过CCP EATT链路通知耳机准备通话,并断开原有音乐CIS连接。随后建立通话专用的CIG组,其参数设置(如MAX SDU SIZE=80、RTN=2)与音乐场景明显不同,更注重通话的实时性。文中详细描述了设置ISO数据路径、启用ASE、建立CIS连接等关键步骤,特别指出通话采用Conversational音频上下文类型。最后解析了ISO数据包参数含义,展示了10ms周期、32kHz采样率等通话特性参数。整个过程体现了BLE AUDIO

十多年蓝牙协议软件开发,擅长蓝牙协议分析 1873

springcache使用condition无法缓存数据

Cacheable的 condition 属性能使用的 SpEL 语言只有 #root 和获取参数类的 SpEL 表达式,不能使用返回结果的 #result,当我们想在返回值为空的情况不进行数据缓存,可以使用 unless,unless 的作用和 condition 的作用刚好相反,在使用springcache进行数据缓存的时候,有时候我们会有一个很常用的需求:我们希望在函数的返回值为空的情况下不进行数据缓存(,然后测试的时候发现居然没有缓存数据。

qq_1732628250的博客 712

手把手教你玩转CPU微架构专栏--​​​​1.5 工具准备:用Gem5模拟器“看见”微架构(安装、基础仿真命令)​

本文介绍了如何使用Gem5模拟器进行微架构学习和实验。Gem5是一款支持多种指令集的开源微架构模拟器,可模拟CPU流水线、缓存等核心组件。文章详细说明了在Ubuntu和macOS上安装Gem5的步骤,包括依赖安装、源码编译和验证方法。通过一个简单的加法指令测试程序,演示了如何运行基础仿真并解读输出日志,包括指令执行流程和性能统计数据。此外,还提供了两个实战实验:修改L1缓存大小和观察分支预测失败,帮助读者理解微架构参数对性能的影响。最后指出Gem5是学习微架构的"显微镜",能直观观察指令

xiaoheshang_123的博客 144

安全与加密常识(10)linux系统证书管理

1. 将自定义CA证书(如my-ca.crt)放到源目录# 2. 编辑配置文件,启用该证书(末尾添加一行 my-ca.crt)# 3. 执行命令同步(核心工作环节)# 4. 验证结果:检查是否生成哈希链接和合并到证书束ls /etc/ssl/certs/my-ca.pem # 证书文件ls /etc/ssl/certs/$(openssl x509 -hash -noout -in /usr/share/ca-certificates/my-ca.crt).0 # 哈希链接。

二进制君 302

Spring缓存抽象:@Cache注解深度解析与最佳实践指南

if (param!= null) {} else {// 使用// ...缓存选择本地缓存:高性能、单机场景(Caffeine)分布式缓存:集群环境(Redis)键设计原则唯一性:不同参数产生不同键可读性:包含业务含义简洁性:避免过长键值失效策略TTL+随机抖动:防雪崩主动失效:数据变更时立即失效监控指标命中率:>80%为健康加载时间:<50ms内存使用:<70%最大限制重要提醒缓存不是万能的,不合理的使用反而会降低系统性能。始终基于性能测试和监控数据做决策。

xiaoyu❅的博客 1577

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

cacheput注解 用法_Spring缓存注解@Cache使用

一、 缓存注解有以下三个:@Cacheable@CacheEvict@CachePut@Cacheable(value=”accountCache”),这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 userName,value...

weixin_31134719的博客 4229

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

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Spring缓存注解@Cache,@CachePut , @CacheEvict,@CacheConfig使用

@Cacheable、@CachePut、@CacheEvict 注释介绍 表 1. @Cacheable 作用和配置方法 @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @Cacheable 主要的参数 value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cac

Sanjay的专栏 9万+

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

spring @cache缓存注解

spring @cache缓存注解 转至[https://www.cnblogs.com/fashflying/p/6908028.html]

l984411392的博客 208
上一篇: maven常用命令
下一篇: eclipse使用技巧
MarkArch
博客等级 码龄12年 35粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值