1. 程式人生 > >企業級框架____Ehcache快取框架(Ehcache和Spring的整合)

企業級框架____Ehcache快取框架(Ehcache和Spring的整合)

//======整合結構圖


//==建立專案新增spring依賴和Rhcache的jar包

jdbc的資料來源jar包 這是spring啟動必備的一個

ehcache.包和它依賴的包sf4j

Ehcache的結構


//==配置spring的applicationContext.xml配置檔案

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
		
<!-- springconfigStart -->
	
	<!-- 使用註解的方式裝配置bean -->
	<context:annotation-config />
	<context:component-scan base-package="com.frame"></context:component-scan>
	<!-- 配置dbcp資料來源  -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
		<property name="username" value="oracle" />
		<property name="password" value="123456" />
	</bean>




<!-- 開啟spring的快取註解   -->
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache.xml"></property>  
    </bean>  
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="ehcache"></property>  
    </bean>  
	<cache:annotation-driven cache-manager="cacheManager" />
	
	
<!-- springconfigEnd  -->
</beans>

配置jdbc檔案

#log4j輸出選項
#log4j.rootLogger=info,stdout,file
log4j.rootLogger=info,file
#輸出到控制檯
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.ImmediateFlush=true   
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout   
#log4j.appender.stdout.layout.ConversionPattern=-----------------------------------------------------------------------------------%nLevel:[%p]%nTime:[%d]%nClass:[%c]%nMessage:[%m]%n
#寫入到根目錄
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=${logpath}/logs/log_info.log
log4j.appender.file.encoding=UTF-8
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss,SSS}_%t method\:%l%n%m%n
//配置ehcache.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
   <!-- 指定一個檔案目錄,當EhCache把資料寫到硬碟上時,將把資料寫到這個檔案目錄下 -->
    <diskStore path="java.io.tmpdir"/>

    <!-- 設定快取的預設資料過期策略 -->
    <defaultCache
            maxElementsInMemory="10000" 
            eternal="false" 
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <cache name="simpleCache"
        maxElementsInMemory="1000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="10"
        timeToLiveSeconds="20"/>
  
</ehcache>

//配置student實體類
package com.frame.student.bean;
/**
 * Student entity. @author MyEclipse Persistence Tools
 */
public class Student implements java.io.Serializable {

	
	/**
	 * SRRID
	 */
	private static final long serialVersionUID = -5076741984769526094L;
	
	// Fields
	private String stuid;
	private String stuname;
	private String stupwd;
	private String createtime;

	// Constructors
	/** default constructor */
	public Student() {
	}

	/** minimal constructor */
	public Student(String stuid) {
		this.stuid = stuid;
	}

	/** full constructor */
	public Student(String stuid, String stuname, String stupwd,
			String createtime) {
		this.stuid = stuid;
		this.stuname = stuname;
		this.stupwd = stupwd;
		this.createtime = createtime;
	}

	// Property accessors

	public String getStuid() {
		return this.stuid;
	}

	public void setStuid(String stuid) {
		this.stuid = stuid;
	}

	public String getStuname() {
		return this.stuname;
	}

	public void setStuname(String stuname) {
		this.stuname = stuname;
	}

	public String getStupwd() {
		return this.stupwd;
	}

	public void setStupwd(String stupwd) {
		this.stupwd = stupwd;
	}

	public String getCreatetime() {
		return this.createtime;
	}

	public void setCreatetime(String createtime) {
		this.createtime = createtime;
	}

}
//配置dao和實現類
package com.frame.student.dao;

import com.frame.student.bean.Student;

public interface StudentDao {

	/**
	 * 測試下ehcache的快取機制
	 * @param param
	 * @return
	 */
	public Student testEcache(String stuid);
	
	
}
package com.frame.student.dao;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.frame.student.bean.Student;

@Repository
public class StudentDaoImpl implements StudentDao{
	
	
//或者模擬假資料
	
	@Cacheable(value = "simpleCache", key = "#stuid")
	@Override
	public Student testEcache(String stuid) {
		System.out.println("開始訪問資料庫");
		Student sdf=new Student();
		sdf.setStuid(stuid);
		return sdf;
	}

}

//ehcache簡單使用
package com.frame.base.ehcache;

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

public class TestCache {
	public static void main(String[] args) throws Exception {
		//初始化Ehcahce物件
		CacheManager cacheManager = new CacheManager();
		//載入自定義cache物件
		Cache cache = cacheManager.getCache("simpleCache");
		//把集合放入快取  存放鍵值對集合類似map
		cache.put(new Element("user", "zhangsan"));
		//取出集合根據key獲取值
		System.out.println("key=user value=:"+cache.get("user").getObjectValue());
		//更新集合的key=user的值
		cache.put(new Element("user", "lisi"));
		System.out.println("key=user value=:"+cache.get("user").getObjectValue());
		//獲取快取中的原素個數
		System.out.println("集合個數:"+cache.getSize());
		//移除cache某個值
		cache.remove("user");
		System.out.println("集合個數:"+cache.getSize());
		// 關閉當前CacheManager物件
		cacheManager.shutdown();
	}
}


//測試註解型快取機制

package com.frame.student.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.frame.student.dao.StudentDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class StudentTest {
	
	@Resource
	private StudentDao dao;

	@Test
	public void getUserbyId() throws Exception{
		String stuid="10086";
		System.out.println("ehcache.xml配置的超時時間為10秒");
		
		System.out.println("第一次呼叫:"+dao.testEcache(stuid).getStuid());
		
		Thread.sleep(2000);
		System.out.println("2秒後呼叫:"+dao.testEcache(stuid).getStuid());
		
		Thread.sleep(9000);
		System.out.println("9秒後呼叫:"+dao.testEcache(stuid).getStuid());
		
		Thread.sleep(11000);
		System.out.println("11秒後呼叫:"+dao.testEcache(stuid).getStuid());
		
	}
	
	
}



//原始碼: http://pan.baidu.com/s/1pLuQre7