码迷,mamicode.com
首页 > 编程语言 > 详细

缓存插件 Spring支持EHCache缓存

时间:2015-04-21 01:47:23      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

  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/beans
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.1.xsd
     http://www.springframework.org/schema/cache
     http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
     http://www.springframework.org/schema/aop
     http://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/beans
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.1.xsd
     http://www.springframework.org/schema/cache
     http://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")
    @Override
    public Object select(int id) {
        System.out.println("do in function select()");
        return new Object();
    }

    @CacheEvict(value = { "dao.select" }, key="#obj")
    @Override
    public 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
 
例如:

//清除掉指定key的缓存
@CacheEvict(value="andCache",key="#user.userId + ‘findById‘")
public void modifyUserRole(SystemUser user) {
  System.out.println("hello andCache delete"+user.getUserId());
}
&nbsp;//清除掉全部缓存
@CacheEvict(value="andCache",allEntries=true)
public final void setReservedUsers(String[] reservedUsers) {
  System.out.println("hello andCache deleteall");
}

 

缓存插件 Spring支持EHCache缓存

标签:

原文地址:http://www.cnblogs.com/hwaggLee/p/4443155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!