ricardojou
ricardojou
2013-03-13 18:42
采纳率: 66.7%
浏览 430
已采纳

spring整合ehcache缓存不了数据

大部分按照这个帖子上面说的做的http://www.cnblogs.com/lcuzhanglei/archive/2012/05/31/2528124.html,
但是数据就是缓存不了,每次测试都访问数据库。网上也没搜到答案
这个是我的ehcache.xml配置文件
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>

xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect">



maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>

maxElementsInMemory="10000"
maxElementsOnDisk="1000"
eternal="false"
overflowToDisk="true"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
/>



[/code]
spring配置文件
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>
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">


classpath:ehcache.xml













.*getAllDept








methodCachePointcutAdvisor




[/code]
监听器
[code="java"]
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;
}

}

[/code]
访问数据库的类
[code="java"]
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 getAllDept(){
String sql = "select * from dept";
List list = new ArrayList();
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;
}
}

[/code]
实体类
[code="java"]
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;
}

}

[/code]
测试代码
[code="java"]
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());
    }
}

}
[/code]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • qq415241704
    qq415241704 2013-03-14 21:23
    已采纳

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

    点赞 评论
  • qq595105376
    qq595105376 2013-03-14 10:39

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

    timeToLiveSeconds="600"

           timeToIdleSeconds="30000"    
           timeToLiveSeconds="60000"
    
    点赞 评论
  • liudehuas
    liudehuas 2013-03-15 13:54

    [code="java"]

      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());  
        } 
     }
    

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

    点赞 评论

相关推荐