springboot下及其方便的使用缓存

来源:互联网 发布:ubuntu虚拟机nat联网 编辑:程序博客网 时间:2024/05/18 19:39

缓存的提供商是:ehcache

只需要很少的代码就能实现缓存.

1 开启spring缓存

@EnableCachingpublic class XxxxApplication extends SpringBootServletInitializer{}

2 ehcache.xml中定义一个缓存

<?xml version="1.0" encoding="UTF-8"?><ehcache name="com.xxx.core.cache"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">    <!--        新定义一个查询类缓存.        常用的查询,也放进缓存,提升性能.        比如首页的几个查询    -->    <cache name="com.xxx.QUERY_CACHE"           maxElementsInMemory="1000"           eternal="false"           overflowToDisk="false"           timeToIdleSeconds="3600000"           timeToLiveSeconds="3600000"           memoryStoreEvictionPolicy="LFU" /></ehcache>

3 指定缓存服务商

<bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">        <property name="configLocation" value="classpath:/spring/ehcache.xml" />        <property name="shared" value="false" />    </bean>    <bean id="serviceCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">        <property name="cacheManager">            <ref bean="springCacheManager" />        </property>    </bean>    <bean id="serviceCache" factory-bean="serviceCacheManager" factory-method="getCache">        <constructor-arg value="com.shopizer.OBJECT_CACHE" />    </bean>

4 代码中使用

@Cacheable(value="com.xxx.QUERY_CACHE")public List<ProductRelationship> getByType(MerchantStore store, String type, Language language)(当命中的时候,根本不进getByType这个方法的)