有這個想法是在很早之前了,那時的我沒有接觸什麼緩存技術,只知道hibernate有個二級緩存。沒有用過memcache,也沒有使用過redis。java
只懂得將數據放到數組裏或者集合裏,一直不去銷燬它(只有隨着tomcat服務中止而銷燬),用的時候從內存中讀取就至關於緩存了,可是這麼作有利也有弊。redis
好處:操做方便,隨時取,隨時存,只要方法封裝好,代碼也很清晰,易擴展。spring
弊端:由於只要一重啓服務器,放在內存中的靜態集合或靜態數組確定被回收了。致使一些重要的數據被幹掉了。數據庫
話題扯遠了,本文所講的就是如何在spring 加載完畢後監聽它的事件,而且保證只初始化一次。apache
配置其實很簡單,以下:數組
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jaxws="http://cxf.apache.org/jaxws" 7 xmlns:soap="http://cxf.apache.org/bindings/soap" xmlns:jaxrs="http://cxf.apache.org/jaxrs" 8 xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd 9 http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd 10 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 11 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 12 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd 13 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 14 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 15 http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> 16 17 <!-- 初始化引擎使用 --> 18 <bean id="InitDataListener" class="cfs.wsdl.cache.InitDataListener"> 19 <property name="dao"> 20 <ref bean="commonBaseDaoHib" /> 21 </property> 22 </bean> 23 24 25 26 </beans>
1 package cfs.wsdl.cache; 2 3 import java.util.Date; 4 import java.util.List; 5 import java.util.UUID; 6 7 import org.springframework.beans.factory.InitializingBean; 8 9 import com.google.gson.JsonObject; 10 import cfs.core.dao.CommonBaseDao; 11 12 13 14 public class InitDataListener implements InitializingBean { 15 16 private CommonBaseDao dao; 17 18 public CommonBaseDao getDao() { 19 return dao; 20 } 21 22 public void setDao(CommonBaseDao dao) { 23 this.dao = dao; 24 } 25 26 @Override 27 public void afterPropertiesSet() throws Exception { 28 //將須要緩存的數據從數據庫裏緩存到內存中 29 30 31 //啓動一個線程線程: 32 new Thread() { 33 public void run() { 34 while (true) { 35 try { 36 37 38 //這裏寫一些須要定時執行的代碼 39 40 41 //休眠30分鐘,半個小時執行一次 42 Thread.sleep(60 * 1000*30); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 } 47 }; 48 }.start(); 49 50 51 } 52 53 54 55 56 57 }