springboot 整合缓存(Ehcache或者reids)

这里介绍Spring Boot结合JPA,MySQL和Ehcache实现缓存功能,提高程序访问效率。

一、Maven依赖

  

<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

二、程序的启动类加上 @EnableCaching

3、application.yml和ehcache.xml配置文件 

application.yml
#使用ehcache缓存配置
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<cache name="sysCache"
maxElementsInMemory="100000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
memoryStoreEvictionPolicy="LRU"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
4、使用 

注意:
1)@CacheConfig(cacheNames = {“lemonCache”})设置了ehcache的名称,这个名称就是ehcache.xml内的名称; (可以不指定,应为在yml 中已经制定了)
2)@Cacheable:应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调 用方法获取数据,然后把数据添加到缓存中,适用于查找;
3)@CachePut:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用。适用于更新和插入;
4)@CacheEvict:主要针对方法配置,能够根据一定的条件对缓存进行清空。适用于删除。

整合reids   https://blog.csdn.net/plei_yue/article/details/79362372

猜你喜欢

转载自www.cnblogs.com/xiaowangbangzhu/p/10558029.html