SpringBoot 缓存

来源:互联网 发布:什么软件适合iphonex 编辑:程序博客网 时间:2024/06/07 01:02

缓存可以缓解数据库访问的压力,Spring自身不提供缓存的存储实现,需要借助第三方,比如JCache、EhCache、Hazelcast、Redis、Guava等。Spring Boot可以自动化配置合适的缓存管理器(CacheManager),默认采用的是ConcurrentMapCacheManager(java.util.concurrent.ConcurrentHashMap)

1. 添加依赖

    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-cache</artifactId>    </dependency>

2. 为要缓存数据的接口添加注解@Cacheable
Spring 在执行 @Cacheable标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件

 @Cacheable(value = "xxx")

3. 程序入口添加 @EnableCaching注解来开启SpringBoot的缓存支持

4. 集成EhCache
创建文件 src/main/resources/ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:noNamespaceSchemaLocation="ehcache.xsd">      <cache name="user" maxEntriesLocalHeap="200" timeToLiveSeconds="600">      </cache>  </ehcache> 

程序入口添加代码

@Bean      public EhCacheCacheManager cacheManager() {          return new EhCacheCacheManager(ehCacheCacheManager().getObject());      }      @Bean      public EhCacheManagerFactoryBean ehCacheCacheManager() {          EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();          cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));          cmfb.setShared(true);          return cmfb;      }  

遇到问题Element does not allow nested elements
xml文件中xxx标签下面不允许有xxxx元素,删除就好了