spring 缓存 @CachePut 和 @Cacheable 区别
来源:互联网 发布:淘宝网男鞋货到付款 编辑:程序博客网 时间:2024/06/05 01:00
首先这两个的区别是:
@CachePut:这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中。
@Cacheable:当重复使用相同参数调用方法的时候,方法本身不会被调用执行,即方法本身被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。
那么对于@CachePut这个注解,它的作用是什么呢,每次方法都执行,那么缓存的意义是什么呢?在这里写了一个小实例对这两个标签进行测试,并解释了上边这个疑问。
首先,我们猜想对于同一个缓存实例的相同的key的缓存的数据,可以用@CachePut更新,而@Cacheable在取值的时候,是@CachePut更新后的值。
先看看service:
@Cacheable(value="userCache",key="1000")public String getUserByName(String userName) { System.out.println("两次调用第一次会执行,第二次不会执行!"); return getFromDB(userName); } @CachePut(value="userCache",key="1000")public String updateUserPut(String userName) { return updateDB(userName); }
注意这里的key定义的都是1000,缓存的实例都是userCache
测试方法:
// 加载 spring 配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("com/spricache/config/spring-cache.xml"); UserService userService = (UserService) context.getBean("userService"); //会查询 System.out.println(userService.getUserByName("txxs")); //会走缓存 System.out.println(userService.getUserByName("txxs")); //更新名字,会走数据库 System.out.println(userService.updateUserPut("txxsNew")); //会走缓存呢,还是数据库呢? System.out.println(userService.getUserByName("txxsNew"));
执行的结果:
两次调用第一次会执行,第二次不会执行!
正在从数据库查询txxs
txxs
txxs
更新数据库txxsNew
txxsNew
txxsNew
我们来分析这个结果:System.out.println(userService.getUserByName("txxs"));被执行两次,第一次是从数据库中取值,第二次是从缓存中取值,这和我们之前所了解的缓存用法是一样的。那么我们调用System.out.println(userService.updateUserPut("txxsNew"));这个方法会更新数据库中的名字,注意这里的key值我们定义的是1000,也就是会更新userCache中key为1000的值,然后将会返回的结果,这里我们也做了一个输出操作,也就是第一个txxsNew。然后再调用System.out.println(userService.getUserByName("txxsNew"));获取key为1000的名字,输出的结果是txxsNew,正是updateUserPut方法更新后的缓存的值。
总结:@CachePut和@Cacheable这两个标签可以结合使用,当需要根据请求改变值的时候,利用@CachePut将值改变并写入到缓存中,而@Cacheable标签除了第一次之外,[email protected]�点:
1、必须是同一个缓存实例。
2、key值必须是相同的。
- spring 缓存 @CachePut 和 @Cacheable 区别
- spring 缓存 @CachePut 和 @Cacheable 区别
- Spring缓存注解@Cacheable、@CachePut和@CacheEvict
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用
- Spring 缓存注解(@Cacheable、@CachePut、@CacheEvict)使用
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- Spring缓存注解@Cacheable,@CachePut , @CacheEvict介绍
- Spring缓存Cache,Cacheable,CachePut使用
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
- 【技能库】@Cacheable @CachePut Spring 缓存示例(142)
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用注意点
- @Cacheable、@CachePut和@CacheEvict介绍
- @Cacheable、@CachePut和@CacheEvict介绍
- spring整合redis缓存,以注解(@Cacheable、@CachePut、@CacheEvict)形式使用
- 打开和保存文件对话框
- 嵌入式Linux学习路线图
- 【b504】等价表达式(NOIP2005第4题)
- PHP编译安装
- Http跨站点请求伪造解决方案
- spring 缓存 @CachePut 和 @Cacheable 区别
- 2016年中国设备管理大会暨第十四届全国TnPM大会
- 提示、警告、错误、询问、关于对话框
- 【杭电1213】How Many Tables
- Android之Path类
- C#控制台 hello world之 用类的属性输出
- easy中datagrid联动总结
- 负载均衡
- C语言实现服务端和客户端进行TCP通信实例