没有合适的资源?快使用搜索试试~ 我知道了~
声明方法:编写具体实现:只有符合条件的 id 才会被缓存,而不符合条件的则会调用真实方法查询数据。@CacheEvict 注解。使用详见官方文档:使用 allE
资源详情
资源评论
资源推荐
缓存概述:
Since version 3.1, the Spring Framework provides support for
transparently adding caching to an existing Spring application. Similar
to the transaction support, the caching abstraction allows consistent use
of various caching solutions with minimal impact on the code.
As from Spring 4.1, the cache abstraction has been significantly improved
with the support of JSR-107 annotations and more customization options.
翻译:
自 3.1 版本以来,Spring 框架提供了对向现有 Spring 应用程序透明地添加缓存
的支持。与事务支持类似,缓存抽象允许在对代码影响最小的情况下一致使用各
种缓存解决方案。
从 Spring 4.1 开始,在 JSR-107 注释和更多定制选项的支持下,缓存抽象得到
了显著改进。
At its core, the cache abstraction applies caching to Java methods, thus
reducing the number of executions based on the information available in
the cache. That is, each time a targeted method is invoked, the abstraction
applies a caching behavior that checks whether the method has been already
executed for the given arguments. If it has been executed, the cached
result is returned without having to execute the actual method. If the
method has not been executed, then it is executed, and the result is cached
and returned to the user so that, the next time the method is invoked,
the cached result is returned. This way, expensive methods (whether CPU-
or IO-bound) can be executed only once for a given set of parameters and
the result reused without having to actually execute the method again.
The caching logic is applied transparently without any interference to
the invoker.
缓存抽象的核心是将缓存应用于 Java 方法,从而根据缓存中可用的信息减少执
行次数。也就是说,每次调用目标方法时,抽象都会应用缓存行为来检查是否已
经为给定参数执行了该方法。如果已经执行,则返回缓存的结果,而不需要执行
实际的方法。如果还没有执行该方法,那么就会执行该方法,并将结果缓存并返
回给用户,以便在下一次调用该方法时返回缓存的结果。这样,对于给定的一组
参数和重用的结果,昂贵的方法(无论是 CPU 绑定的还是 io 绑定的)只能执行一
次,而不必再次实际执行该方法。缓存逻辑透明地应用,不会对调用程序造成任
何干扰。
总体上来说呢,Spring Cache 并不是一些缓存方案的具体实现,而是一个对缓
存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够
达到缓存方法的返回对象的效果。Spring Cache 还支持使用 SPEL(Spring
Expression Language)来定义缓存的 key 和各种 condition,在实际开发中具
有很高的灵活性。
基于注解的缓存:
Spring 缓存提供了以下注解来实现缓存:
@Cacheable:触发器缓存人口。
@CacheEvict: 触发缓存回收。
@CachePut:在不影响方法执行的情况下更新缓存。触发缓存回收。
@Caching: 重新组合要应用于方法的多个缓存操作。
@CacheConfig:在类级别上共享一些常见的缓存相关设置。
本次呢,主要集中讲解@Cacheable,@CacheEvict,@CachePut 这三个注解的使用
配置 Spring Cache
首先呢,我们先声明一个配置类 CacheConfig,并在配置类上加上@EnableCaching
和@Configuration 注解。
@EnableCaching 注解是 spring framework 中的注解驱动的缓存管理功能。自 spring
版本 3.1 起加入了该注解。如果你使用了这个注解,那么你就不需要在 XML 文件
中配置 cache manager 了。
@Configuration:声明一个 java 配置类
这里我们定义一个缓存管理器 simpleCacheManager,通过名字呢大致可以猜测到
这个缓存管理器实现了 SpringCache 基本的功能,至于后续更加详细的解读,后
续文章会提到。
然后构造一个缓存的对象 ConcurrentMapCache,其中构造器参数即是我们为缓
存定义的名称,其中,一个 Spring 应用中允许存在多个缓存。
通过 SimpleCacheManager.的 setCaches 方法把我们的缓存对象和缓存管理器进行
绑定。
缓存的简单使用:
剩余12页未读,继续阅读
嗨了伐得了
- 粉丝: 16
- 资源: 290
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0