0 0

spring整合ehcache缓存不了数据5

大部分按照这个帖子上面说的做的http://www.cnblogs.com/lcuzhanglei/archive/2012/05/31/2528124.html,
但是数据就是缓存不了,每次测试都访问数据库。网上也没搜到答案
这个是我的ehcache.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"  
    monitoring="autodetect">  
    <diskStore path="d:\\temp\\cache"/>  
    <defaultCache  
            maxElementsInMemory="10000"  
            eternal="false"  
            timeToIdleSeconds="120"  
            timeToLiveSeconds="120"  
            overflowToDisk="true"  
            maxElementsOnDisk="10000000"  
            diskPersistent="false"  
            diskExpiryThreadIntervalSeconds="120"  
            memoryStoreEvictionPolicy="LRU"  
            />  
     <cache name="demoCache"  
           maxElementsInMemory="10000"  
           maxElementsOnDisk="1000"  
           eternal="false"  
           overflowToDisk="true"  
           diskSpoolBufferSizeMB="20"  
           timeToIdleSeconds="300"  
           timeToLiveSeconds="600"  
           memoryStoreEvictionPolicy="LFU"  
            />  
</ehcache>  

spring配置文件
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
			default-lazy-init="true">
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation">
			<value>classpath:ehcache.xml</value>
		</property>
	</bean>
	<bean id="deptCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
		<property name="cacheManager" ref="cacheManager"/>
		<property name="beanName" value="democache"/>
	</bean>
	<bean id="cacheInterceptor" class="com.xiaolu.interceptor.MethodCacheInterceptor">
		<property name="cache" ref="deptCache"/>
	</bean>
	<bean id="methodCachePointcutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="advice" ref="cacheInterceptor"/>
		<property name="patterns">
			<list>
				<value>.*getAllDept</value>
			</list>
		</property>
	</bean>
	<bean id="deptService" class="com.xiaolu.service.DeptService"/>
	<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="target" ref="deptService"/>
		<property name="interceptorNames">
			<list>
				<value>methodCachePointcutAdvisor</value>
			</list>
		</property>
	</bean>
</beans>

监听器
package com.xiaolu.interceptor;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class MethodCacheInterceptor implements MethodInterceptor,InitializingBean {
	private Cache cache;
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String targetName = invocation.getThis().getClass().getName();
		String methodName = invocation.getMethod().getName();
		Object[] arguments = invocation.getArguments();
		Object result = null;
		String cacheKey = getCacheKey(targetName, methodName, arguments);
		System.out.println("cacheKey:"+cacheKey);
		Element element = null;
		System.out.println("-----1-----");
		synchronized(this){
			element = cache.get(cacheKey);
			if(null == element){
				result = invocation.proceed();
				System.out.println("-----2----");
				element = new Element(cacheKey, (Serializable)result);
				cache.put(element);
			}
		}
		return element.getValue();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(cache,
				"A cache is required. Use setCache(Cache) to provide one.");
	}
	private String getCacheKey(String targetName,String methodName,Object[] arguments){
		StringBuilder sb = new StringBuilder();
		sb.append(targetName).append(".").append(methodName);
		if((arguments.length !=0)&&(arguments != null)){
			for(int i=0;i<arguments.length;i++){
				sb.append(".").append(arguments[i]);
			}
		}
		return sb.toString();
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

}


访问数据库的类
package com.xiaolu.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.xiaolu.pojo.Dept;

public class DeptService {
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public List<Dept> getAllDept(){
		String sql = "select * from dept";
		List<Dept> list = new ArrayList<Dept>();
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()){
				Dept dept = new Dept();
				dept.setDeptno(rs.getInt("deptno"));
				dept.setDname(rs.getString("dname"));
				dept.setLoc(rs.getString("loc"));
				list.add(dept);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}


实体类
package com.xiaolu.pojo;

import java.io.Serializable;

public class Dept implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int deptno;
	private String dname;
	private String loc;
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
}


测试代码
package test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xiaolu.pojo.Dept;
import com.xiaolu.service.DeptService;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class Test {
	public static void main(String[] args) {
		
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		DeptService service = (DeptService) context.getBean("proxyFactoryBean");
		List<Dept> list = service.getAllDept();
		for(Dept dept:list){
			System.out.println(dept.getDname());
		}
	}
}
2013年3月13日 18:42

3个答案 按时间排序 按投票排序

0 0

采纳的答案

你测试方法有问题,在测试类里面new出ClassPathXmlApplicationContext,但是你下面用来从数据库取数据在同一个ClassPathXmlApplicationContext下只有一次,怎么可能会有缓存呢?,等于是每次都是new的不同的ClassPathXmlApplicationContext,每次都是new的不同的cache对象,你需要在测试中连续取几次数据。这样就可以看到结果

2013年3月14日 21:23
0 0


      ApplicationContext context = new  ClassPathXmlApplicationContext("applicationContext.xml");  
        DeptService service = (DeptService) context.getBean("proxyFactoryBean");  
       for(int i=0;i<5;i++){
         List<Dept> list = service.getAllDept();  
        for(Dept dept:list){  
            System.out.println(dept.getDname());  
        } 
     }

在数据库查询方法中 添加日志信息  看查询了几次数据库

2013年3月15日 13:54
0 0

缓存时间设置太短了
           timeToIdleSeconds="300"   
           timeToLiveSeconds="600" 

============================================
           timeToIdleSeconds="30000"   
           timeToLiveSeconds="60000"

2013年3月14日 10:39

相关推荐

Global site tag (gtag.js) - Google Analytics