ssm整合ehcache
1.开始写ehcache.xml进行配置。
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- java.io.tmpdir:Java临时目录。指定一个文件目录,当EhCache把数据写到硬盘上或者系统jvm内存时,将把数据写到这个文件目录下 -->
<diskStore path="java.io.tmpdir"/>
<!-- maxElementsInMemory:设置基于内存的缓存可存放对象的最大数目。 -->
<!-- eternal:如果为true,表示对象永远不会过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false; -->
<!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了 -->
<!-- timeToIdleSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。 -->
<!-- 如果该属性值为0,则表示对象可以无限期地处于空闲状态。 -->
<!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。 -->
<!-- overflowToDisk:如果为true,表示当基于内存的缓存中的对象数目达到了maxElementsInMemory界限后,会把益出的对象写到基于硬盘的缓存中。 -->
<!-- 设定缓存的默认数据过期策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<!-- 自定义缓存策略-学生信息缓存容器对应策略-->
<cache name="myCache"
maxElementsInMemory="1000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"/>
</ehcache>
2.新建spring-ehcache.xml添加ehcache配置。
代码如下(示例):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
<!--配置cache-->
<cache:annotation-driven cache-manager="cacheManager"/>
<!--需要引入ehcache.jar 和 spring-context-support.jar-->
<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"></property>
</bean>
</beans>
3.然后将spring-ehcache.xml文件引入到applicationContext.xml中,保证项目启动时进行加载。
<import resource="spring-ehcache.xml"/>
4.接下来我们就开始写service的逻辑。
package com.lhcc.demo.service;
import com.google.common.base.Optional;
import com.lhcc.demo.entity.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @author wenchao.ren
* 2015/1/5.
*/
@Service
public class AccountService2 {
private final Logger logger = LoggerFactory.getLogger(AccountService2.class);
@Cacheable(value="myCache")
public String query(){
logger.info("real querying account... {}"+"sfdfdsfd");
return "fhsfs";
}
// 使用了一个缓存名叫 accountCache
@Cacheable(value="accountCache")
public Account getAccountByName(String accountName) {
// 方法内部实现不考虑缓存逻辑,直接实现业务
logger.info("real querying account... {}", accountName);
Optional<Account> accountOptional = getFromDB(accountName);
if (!accountOptional.isPresent()) {
throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
}
return accountOptional.get();
}
private Optional<Account> getFromDB(String accountName) {
logger.info("real querying db... {}", accountName);
//Todo query data from database
return Optional.fromNullable(new Account(accountName));
}
}
5.测试
package com.lhcc.demo.test;
import com.lhcc.demo.service.AccountService2;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
public class AccountService2Test {
private AccountService2 accountService2;
private final Logger logger = LoggerFactory.getLogger(AccountService2Test.class);
@Before
public void setUp() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring-cache.xml");
accountService2 = context.getBean("accountService2", AccountService2.class);
}
@Test
public void testInject(){
assertNotNull(accountService2);
}
@Test
public void testGetAccountByName() throws Exception {
logger.info("first query...");
accountService2.getAccountByName("accountName");
logger.info("second query...");
accountService2.getAccountByName("accountName");
}
@Test
public void query() throws Exception {
logger.info("first query...");
accountService2.query();
logger.info("second query...");
accountService2.query();
}
}