java 将ehcache与spring3.0集成

qmelpv7a  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(123)

我有一个使用spring 3.0.2和ibatis的应用程序。现在,我需要将ehcache与我的代码集成。我试过this link,但无法让它工作。我希望有人能给予我所需的jar的细节,要做的xml配置和代码更改,如果需要的话。

mkh04yzy

mkh04yzy1#

升级到最新的spring 3.1里程碑-它通过注解内置了缓存支持-see here
除此之外,您可以始终使用EhCacheFactoryBean

bfrts1fy

bfrts1fy2#

要在应用程序中实现此功能,请执行以下步骤:
第一步:
按照Ehcache Annotations for Spring project site上的列表将jar添加到应用程序中。
第二步:
将Annotation添加到要缓存的方法中。让我们假设你正在使用上面的Dog getDog(String name)方法:

@Cacheable(name="getDog")
Dog getDog(String name)
{
    ....
}

第三步:
配置Spring。您必须在beans声明部分将以下内容添加到Spring配置文件中:

<ehcache:annotation-driven cache-manager="ehCacheManager" />

请参阅Ehcache site了解完整的详细信息。

tjjdgumg

tjjdgumg3#

要集成Ehcache,只需按照以下步骤操作
1 -在pom XML文件中添加依赖关系

<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache-core</artifactId>
   <version>2.6.9</version>
</dependency>

2 -创建一个名为spring-cache.xml的xml文件,将其放入resources文件夹

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
    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.xsd
        http://www.springframework.org/schema/cache 
        http://www.springframework.org/schema/cache/spring-cache.xsd">

    <cache:annotation-driven/>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache" />
    </bean>

    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>

</beans>

3 -正如你所看到的,我们正在使用ehcache.xml的引用,因此创建文件并将其放在resources文件夹中

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">
    <cache name="users" maxEntriesLocalHeap="5000"
        maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="200" timeToLiveSeconds="500"
        memoryStoreEvictionPolicy="LFU" transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>
</ehcache>

因此可以看到为“用户”创建缓存,以便可以在从数据库查询用户列表的任何地方使用
4 -使用它像下面的代码

@Cacheable(value="users")
public List<User> userList() {
    return userDao.findAll();
}

这与在任何需要的地方实现缓存的方式相同
仍然有一些疑问或困惑请看现场演示
Integrate EhCache in Spring MVC

相关问题