对于缓存,有时候是增加效率的好方法。
com.spring.entity.User@911ed70
com.spring.entity.User@911ed70
<cache:annotation-driven cache-manager="cacheManager" />//开启缓存注解
缓存配置
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache">
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:spring-ehcache.xml" p:shared="true"/>
缓存设置
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect">
<!-- 设置缓存文件 .data 的创建路径。
如果该路径是 Java 系统参数,当前虚拟机会重新赋值。
下面的参数这样解释:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径 -->
<diskStore path="java.io.tmpdir"/>
<!--缺省缓存配置。CacheManager 会把这些配置应用到程序中。
下列属性是 defaultCache 必须的:
maxInMemory - 设定内存中创建对象的最大值。
eternal - 设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超
时限制且元素永不消亡。
timeToIdleSeconds - 设置某个元素消亡前的停顿时间。
也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。
这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则
设置该属性也无用)。
如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds - 为元素设置消亡前的生存时间。
也就是一个元素从构建到消亡的最大时间间隔值。
这只能在元素不是永久驻留时有效。
overflowToDisk - 设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘
上。
-->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5000"
timeToLiveSeconds="5000"
overflowToDisk="true"
/>
<cache name="eLearnCache"
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="200"
timeToLiveSeconds="300"
overflowToDisk="true"
/>
</ehcache>
缓存实现
@Cacheable(value="eLearnCache",key="#root.args[0]+'findByName'")
@Query("select u from User u where u.name = ?1")
public User findByName(String name);
缓存测试
System.out.println(loginService.findByName(user.getName()));
System.out.println(loginService.findByName(user.getName()));
测试结果
com.spring.entity.User@911ed70
com.spring.entity.User@911ed70
对象一致,说明缓存注入成功,对于缓存的更新要先清除缓存,以及key值得设置,笔者不一一赘述。