javascript
缓存插件 Spring支持EHCache缓存
Spring僅僅是提供了對緩存的支持,但它并沒有任何的緩存功能的實現,spring使用的是第三方的緩存框架來實現緩存的功能。其中,spring對EHCache提供了很好的支持。
?
在介紹Spring的緩存配置之前,我們先看一下EHCache是如何配置。?
<?xml version="1.0" encoding="UTF-8" ?> <ehcache><!-- 定義默認的緩存區,如果在未指定緩存區時,默認使用該緩存區 --><defaultCache maxElementsInMemory="500" eternal="true"overflowToDisk="false" memoryStoreEvictionPolicy="LFU"></defaultCache><!-- 定義名字為"dao.select"的緩存區 --><cache name="dao.select" maxElementsInMemory="500" eternal="true"overflowToDisk="false" memoryStoreEvictionPolicy="LFU" /> </ehcache>?
?由于Spring的緩存機制是基于Spring的AOP,那么在Spring Cache中應該存在著一個Advice。沒錯,在Spring Cache中的Advice是存在的,它就是org.springframework.cache.Cache。我們看一下它的接口定義:?
/** Copyright 2002-2011 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.cache;/*** Interface that defines the common cache operations.** <b>Note:</b> Due to the generic use of caching, it is recommended that* implementations allow storage of <tt>null</tt> values (for example to* cache methods that return {@code null}).** @since 3.1*/ public interface Cache {/*** Return the cache name.*/String getName();/*** Return the the underlying native cache provider.*/Object getNativeCache();/*** Return the value to which this cache maps the specified key. Returns* <code>null</code> if the cache contains no mapping for this key.* @param key key whose associated value is to be returned.* @return the value to which this cache maps the specified key,* or <code>null</code> if the cache contains no mapping for this key*/ValueWrapper get(Object key);/*** Associate the specified value with the specified key in this cache.* <p>If the cache previously contained a mapping for this key, the old* value is replaced by the specified value.* @param key the key with which the specified value is to be associated* @param value the value to be associated with the specified key*/void put(Object key, Object value);/*** Evict the mapping for this key from this cache if it is present.* @param key the key whose mapping is to be removed from the cache*/void evict(Object key);/*** Remove all mappings from the cache.*/void clear();/*** A (wrapper) object representing a cache value.*/interface ValueWrapper {/*** Return the actual value in the cache.*/Object get();}}?
?evict,put方法就是Advice的功能方法,或者可以這樣去理解。
?但spring并不是直接使用org.springframework.cache.Cache,spring把Cache對象交給org.springframework.cache.CacheManager來管理,下面是org.springframework.cache.CacheManager接口的定義:
/** Copyright 2002-2011 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.cache;import java.util.Collection;/*** A manager for a set of {@link Cache}s.** @since 3.1*/ public interface CacheManager {/*** Return the cache associated with the given name.* @param name cache identifier (must not be {@code null})* @return associated cache, or {@code null} if none is found*/Cache getCache(String name);/*** Return a collection of the caches known by this cache manager.* @return names of caches known by the cache manager.*/Collection<String> getCacheNames();}?
?在spring對EHCache的支持中,org.springframework.cache.ehcache.EhCacheManager就是org.springframework.cache.CacheManager的一個實現
<!-- 該Bean是一個org.springframework.cache.CacheManager對象屬性cacheManager是一個net.sf.ehcache.CacheManager對象--><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"><property name="cacheManager"><bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><property name="configLocation" value="classpath:ehcache-config.xml"></property></bean></property></bean>?
?基于xml方式的緩存配置
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:cache="http://www.springframework.org/schema/cache"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache-3.1.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd"><context:component-scan base-package="com.sin90lzc"></context:component-scan><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"><property name="cacheManager"><bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><property name="configLocation" value="classpath:ehcache-config.xml"></property></bean></property></bean><cache:advice id="cacheAdvice" cache-manager="cacheManager"><cache:caching><cache:cacheable cache="dao.select" method="select"key="#id" /><cache:cache-evict cache="dao.select" method="save"key="#obj" /></cache:caching></cache:advice><aop:config><aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.sin90lzc.train.spring_cache.simulation.DaoImpl.*(..))"/></aop:config> </beans>?
?
?注解驅動緩存配置
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:cache="http://www.springframework.org/schema/cache"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache-3.1.xsd"><context:component-scan base-package="com.sin90lzc"></context:component-scan><!-- 該Bean是一個org.springframework.cache.CacheManager對象屬性cacheManager是一個net.sf.ehcache.CacheManager對象--><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"><property name="cacheManager"><bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><property name="configLocation" value="classpath:ehcache-config.xml"></property></bean></property></bean><cache:annotation-driven /><!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 --><!-- <cache:annotation-driven cache-manager="cacheManager"/> --></beans>?
?
?
?
?
package com.sin90lzc.train.spring_cache.simulation;import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component;@Component public class DaoImpl implements Dao {/*** value定義了緩存區(緩存區的名字),每個緩存區可以看作是一個Map對象* key作為該方法結果緩存的唯一標識,*/@Cacheable(value = { "dao.select" },key="#id")@Overridepublic Object select(int id) {System.out.println("do in function select()");return new Object();}@CacheEvict(value = { "dao.select" }, key="#obj")@Overridepublic void save(Object obj) {System.out.println("do in function save(obj)");}}?
@Cacheable:負責將方法的返回值加入到緩存中
@CacheEvict:負責清除緩存
?@Cacheable 支持如下幾個參數:
value:緩存位置名稱,不能為空,如果使用EHCache,就是ehcache.xml中聲明的cache的name
key:緩存的key,默認為空,既表示使用方法的參數類型及參數值作為key,支持SpEL
condition:觸發條件,只有滿足條件的情況才會加入緩存,默認為空,既表示全部都加入緩存,支持SpEL
?例如:
//將緩存保存進andCache,并使用參數中的userId加上一個字符串(這里使用方法名稱)作為緩存的key @Cacheable(value="andCache",key="#userId + 'findById'") public SystemUser findById(String userId) {SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);return user ; } //將緩存保存進andCache,并當參數userId的長度小于32時才保存進緩存,默認使用參數值及類型作為緩存的key @Cacheable(value="andCache",condition="#userId.length < 32") public boolean isReserved(String userId) {System.out.println("hello andCache"+userId);return false; }?
?@CacheEvict 支持如下幾個參數:
value:緩存位置名稱,不能為空,同上
key:緩存的key,默認為空,同上
condition:觸發條件,只有滿足條件的情況才會清除緩存,默認為空,支持SpEL
allEntries:true表示清除value中的全部緩存,默認為false
?
例如:
?
轉載于:https://www.cnblogs.com/hwaggLee/p/4443155.html
總結
以上是生活随笔為你收集整理的缓存插件 Spring支持EHCache缓存的全部內容,希望文章能夠幫你解決所遇到的問題。