`

自己实现cache方法 spring-cache.xml

 
阅读更多
最近比较无聊,就自己写了一个Cache,已经实现了大概的功能

一.Cache缓存接口类
public interface Cache extends java.lang.Comparable {

// 放入元素  
void put(CacheElement element) throws CacheException;

// 获取元素
CacheElement get(String key) throws CacheException;

// 重新刷新缓存
void refresh();

void list();

// 获取缓存的key
Set<String> getKeys();

void remove(String key);

// 清除缓存
void clear();

int getSize();

String getName();

void setName(String name);

String toString();

}

二。Storage 存取器接口,主要的实现类有 MemoryStorage,DiskStorage,MixStorage




Java代码 
1.public interface Storage<K, V> { 
2. 
3.    // 能够容纳的最大存储对象。 
4.    public int getMaxElementCnt(); 
5. 
6.    public CachePolicy getCachePolicy(); 
7. 
8.    // 存活时间,当存取器的对象超出等待时间,会自动从存取器中remove, 
9.    // 当是0时,表示对象可以永远等待,不会过期 
10.    public long getIdelSecond(); 
11. 
12.    // 存活时间,当存取器的对象超出存活时间,会自动从存取器中remove 
13.    // 当是 0时,表示永远存活,不会过期 
14.    public long getLiveSecond(); 
15. 
16.    // refresh缓存,将更存取器的对象访问时间和清除过期的对象 
17.    public void refresh(); 
18. 
19.    public void put(CacheElement<K, V> element) throws CacheException; 
20. 
21.    public CacheElement<K, V> get(String key); 
22. 
23.    public CacheElement<K, V> remove(K key); 
24. 
25.    public abstract void removeAll(); 
26. 
27.    // 根据 CachePolicy自动pickout出CacheElement 
28.    public CacheElement<K, V> pickout(); 
29. 
30.    public abstract void dispose(); 
31. 
32.    public abstract int getSize(); 
33. 
34.    public boolean contain(String key); 
35. 
36.    // 获取缓存key的Set 
37.    public Set<K> getKeys(); 
38. 
39.    // 获取缓存entry的Set 
40.    public Set<V> getEntry(); 
41. 
42.} 

三。实现类MemoryStorage
// 内存取贮



Java代码 
1.public class MemoryStorage<K, V> implements Storage, CacheSerializable<K, V> { 
2. 
3.    private static final long serialVersionUID = 1L; 
4. 
5.    private int maxElementCnt; 
6. 
7.    private Map<K, CacheElement> map; 
8. 
9.    private long idelSecond; 
10. 
11.    private long liveSecond; 
12. 
13.    private CachePolicy policy; 
14. 
15.    private static Object lock = new Object(); 
16. 
17.    public MemoryStorage(int maxElementCnt, long liveSecond, long idelSecond, 
18.            CachePolicy policy) { 
19.        this.maxElementCnt = maxElementCnt; 
20.        this.liveSecond = liveSecond; 
21.        this.idelSecond = idelSecond; 
22.        this.policy = policy; 
23.        this.init(policy); 
24.    } 
25. 
26.    public MemoryStorage(int maxElementCnt) { 
27.        this(maxElementCnt, 2, 2, CachePolicy.LFU); 
28.    } 
29.     
30.     
31.    public MemoryStorage() { 
32.        this(1000, 0, 0, CachePolicy.LRU); 
33.    } 
34. 
35.    public CachePolicy getCachePolicy() { 
36.        return policy; 
37.    } 
38. 
39.    public int getMaxElementCnt() { 
40.        return maxElementCnt; 
41.    } 
42. 
43.    public long getIdelSecond() { 
44.        return idelSecond; 
45.    } 
46. 
47.    public void setIdelSecond(long idelSecond) { 
48.        this.idelSecond = idelSecond; 
49.    } 
50. 
51.    public long getLiveSecond() { 
52.        return liveSecond; 
53.    } 
54. 
55.    public void setLiveSecond(long liveSecond) { 
56.        this.liveSecond = liveSecond; 
57.    } 
58. 
59.    public void setMaxElementCnt(int maxElementCnt) { 
60.        this.maxElementCnt = maxElementCnt; 
61.    } 
62. 
63.    private boolean isFull() { 
64.        return this.getMaxElementCnt() == this.getSize(); 
65.    } 
66. 
67.    public void refresh() { 
68.        Set<K> keySet = this.map.keySet(); 
69.        if (keySet == null || keySet.isEmpty()) 
70.            return; 
71.        Iterator<K> it = keySet.iterator(); 
72.        CacheElement element = null; 
73.        Collection<K> collections = new ArrayList<K>(); 
74.        synchronized (lock) { 
75.            while (it.hasNext()) { 
76.                K next = it.next(); 
77.                element = (CacheElement) this.map.get(next); 
78.                if (element.isExpired()) { 
79.                    collections.add(next); 
80.                } 
81.            } 
82.            if (collections.size() > 0) { 
83.                for (K k : collections) { 
84.                    this.map.remove(k); 
85.                } 
86.            } 
87.            long curTime = System.currentTimeMillis(); 
88.            keySet = this.map.keySet(); 
89.            if (keySet == null || keySet.isEmpty()) 
90.                return; 
91.            it = keySet.iterator(); 
92.            while (it.hasNext()) { 
93.                element = this.map.get(it.next()); 
94.                element.setUpdateTime(curTime); 
95.            } 
96.        } 
97. 
98.    } 
99. 
100.    public void dispose() { 
101.        // TODO Auto-generated method stub 
102. 
103.    } 
104. 
105.    public CacheElement<K, V> get(String key) { 
106.        CacheElement<K, V> element = null; 
107.        synchronized (lock) { 
108.            if (this.map.containsKey(key)) { 
109.                element = this.map.get(key); 
110.                element.setUpdateTime(System.currentTimeMillis()); 
111.                element.setHitCnt(element.getHitCnt() + 1L); 
112.            } 
113.            if (this.policy == CachePolicy.LFU) { 
114.                // 对元素按照 hitCnt重新排序 
115. 
116.            } else if (this.policy == CachePolicy.LRU) { 
117. 
118.            } 
119.        } 
120.        return element; 
121.    } 
122. 
123.    public int getSize() { 
124.        return this.map.size(); 
125.    } 
126. 
127.    public void put(CacheElement element) throws CacheException { 
128.        synchronized (lock) { 
129.            if (this.isFull()) { 
130.                this.pickout(); 
131.            } 
132.            if (element != null) { 
133.                element.setStorage(this); 
134.                this.map.put((K) element.getKey(), element); 
135.            } 
136.        } 
137.    } 
138. 
139.    public CacheElement<K, V> remove(Object key) { 
140.        synchronized (lock) { 
141.            if (map.containsKey(key)) { 
142.                return map.remove(key); 
143.            } 
144.        } 
145.        return null; 
146.    } 
147. 
148.    public void removeAll() { 
149.        if (this.map.size() == 0) { 
150.            return; 
151.        } 
152.        synchronized (lock) { 
153.            this.map.clear(); 
154.        } 
155.    } 
156. 
157.    public boolean contain(String key) { 
158.        return this.map.containsKey(key); 
159.    } 
160. 
161.    public Set<K> getKeys() { 
162.        return this.map.keySet(); 
163.    } 
164. 
165.    private void init(CachePolicy policy) { 
166. 
167.        switch (policy) { 
168.        case LFU: 
169.            this.map = new HashMap<K, CacheElement>(); 
170.            break; 
171. 
172.        case FIFO: 
173.            this.map = new LinkedHashMap<K, CacheElement>(); 
174.            break; 
175. 
176.        case LRU: 
177.            this.map = new LinkedHashMap<K, CacheElement>(); 
178.            break; 
179.        } 
180. 
181.    } 
182. 
183.    // 剔除一个元素  
184.    public CacheElement pickout() { 
185.        if (this.getSize() <= 0) { 
186.            return null; 
187.        } 
188.        CacheElement cache = null; 
189.        Set<K> set = null; 
190.        CacheElement[] caches = null; 
191.        Iterator<K> it = null; 
192.        int i = 0; 
193.        switch (policy) { 
194.        case LFU: 
195.            set = this.map.keySet(); 
196.            caches = new CacheElement[set.size()]; 
197.            it = set.iterator(); 
198.            while (it.hasNext()) { 
199.                caches[i++] = this.map.get(it.next()); 
200.            } 
201.            Arrays.sort(caches, new Comparator<CacheElement>() { 
202.                // 按 updateTime升序排列 
203.                public int compare(CacheElement o1, CacheElement o2) { 
204.                    return (int) (o1.getHitCnt() - o2.getHitCnt()); 
205.                } 
206.            }); 
207.            cache = caches[0]; 
208.            this.map.remove(caches[0].getKey()); 
209.            break; 
210. 
211.        case FIFO: 
212.            it = this.map.keySet().iterator(); 
213.            if (it.hasNext()) { 
214.                cache = this.map.remove(it.next()); 
215.            } 
216.            break; 
217.        case LRU: 
218.            set = this.map.keySet(); 
219.            caches = new CacheElement[set.size()]; 
220.            it = set.iterator(); 
221.            while (it.hasNext()) { 
222.                caches[i++] = this.map.get(it.next()); 
223.            } 
224.            Arrays.sort(caches, new Comparator<CacheElement>() { 
225.                // 按 updateTime升序排列 
226.                public int compare(CacheElement o1, CacheElement o2) { 
227.                    return (int) (o1.getUpdateTime() - o2.getUpdateTime()); 
228.                } 
229.            }); 
230.            cache = caches[0]; 
231.            this.map.remove(cache.getKey()); 
232.            break; 
233.        } 
234.        return cache; 
235.    } 
236. 
237.    public Set<V> getEntry() { 
238.        Set set = this.map.entrySet(); 
239.        Iterator<Map.Entry> it = set.iterator(); 
240.        Set<V> entrySet = new TreeSet<V>(); 
241.        while (it.hasNext()) { 
242.            entrySet.add((V) it.next().getValue()); 
243.        } 
244.        return entrySet; 
245.    } 
246. 
247.} 

四。创建Cache的工厂类,CacheManagerFactoryBean



Java代码 
1.public final class CacheManagerFactoryBean { 
2.     
3.    private CacheProvider provider; 
4.     
5.    private String factoryName; 
6.     
7.     
8.    public String getFactoryName() { 
9.        return factoryName; 
10.    } 
11. 
12.    public void setFactoryName(String factoryName) { 
13.        this.factoryName = factoryName; 
14.    } 
15. 
16.    public CacheProvider getProvider() { 
17.        return provider; 
18.    } 
19. 
20.    public void setProvider(CacheProvider provider) { 
21.        this.provider = provider; 
22.    } 
23.  
24.    public final Cache create(){ 
25.         return this.create(null); 
26.    }  
27.     
28. 
29.    public final Cache create(Properties p){   
30.        return  this.getProvider().buildCache(p); 
31.    }  
32. 
33.     
34.} 

五。默认的缓存类实现 DefaultCacheProvider



Java代码 
1.  
2.public class DefaultCacheProvider implements CacheProvider { 
3. 
4.    private String providerName; 
5. 
6.    private Set<Cache> cacheSet; 
7.     
8.    private Properties defaultCacheProperties; 
9.     
10.    private CacheSet cachSet; 
11.     
12.    private static boolean register = false; 
13.     
14.    public CacheSet getCachSet() { 
15.        return cachSet; 
16.    } 
17. 
18.    public void setCachSet(CacheSet cachSet) { 
19.        this.cachSet = cachSet; 
20.    } 
21. 
22.    public DefaultCacheProvider(){  
23.        if( register != true) { 
24.          CacheProviderManager.getInstance().register(  
25.                 this.getClass().getName()+"-"+this.getProviderName(),this); 
26.          register = true;  
27.        } 
28.    } 
29. 
30.    public Properties getDefaultCacheProperties() { 
31.        return defaultCacheProperties; 
32.    } 
33. 
34.    public void setDefaultCacheProperties(Properties defaultCacheProperties) { 
35.        this.defaultCacheProperties = defaultCacheProperties; 
36.    } 
37.     
38.     
39. 
40.    public String getProviderName() { 
41.        return providerName; 
42.    } 
43. 
44.    public void setProviderName(String providerName) { 
45.        this.providerName = providerName; 
46.    } 
47. 
48.  
49.    public Cache buildCache(Properties selfPro) { 
50.            if( this.defaultCacheProperties == null ) { 
51.                 throw new CacheException("请先配置defaultCacheProperties属性"); 
52.            } 
53.            CacheSet cacheSet = new CacheSet(defaultCacheProperties,selfPro); 
54.            Cache cache = new DefaultCacheImpl(cacheSet); 
55.            this.getCaches().add(cache); 
56.            return cache;         
57.    }   
58.     
59.     
60.     
61.    public Set<Cache> getCaches() { 
62.        synchronized(this) { 
63.          if( cacheSet == null) { 
64.              cacheSet  = new TreeSet<Cache>();    
65.          } 
66.        } 
67.        return cacheSet; 
68.    } 
69. 
70. 
71.} 
72.六。cache.xml的spring配置文件 
73.<pre class="java" name="code"><bean id="defaultCacheProvider" class="com.cache.DefaultCacheProvider"  > 
74.          <property name="providerName" value ="defaultProvider">  </property> 
75.          <property name="defaultCacheProperties"> 
76.              <props> 
77.                  <!-- cache的名字 --> 
78.                 <prop key="cache.name">defaultcache</prop> 
79.                 <!-- --> 
80.                 <prop key="cache.cache_policy">LFU</prop> 
81.                 <!-- memory,disk,mix 默认值是  memory  --> 
82.                 <prop key="cache.cache_storage">memory</prop> 
83.                 <!-- 最大存储的最大元素的值  --> 
84.                 <prop key="cache.max_element_count">1000</prop> 
85.                 <!-- 等待时间 ,单位秒,0秒表示可以无限等待 --> 
86.                 <prop key="cache.idel_seconds">1000</prop> 
87.                 <!-- 存活时间 ,单位秒,0秒表示可以永远存活--> 
88.                 <prop key="cache.live_seconds">1000</prop> 
89.            </props> 
90.        </property> 
91.      </bean> 
92.      
93.     <bean id="cacheFactory" class="com.cache.CacheManagerFactoryBean">   
94.             <property name="factoryName" value="defaultCacheFactory" /> 
95.             <property name="provider">   
96.                <ref bean="defaultCacheProvider" />   
97.            </property>  
98.      </bean>   
99.      
100.     <bean id="cache1" class="com.cache.Cache" factory-bean="cacheFactory" factory-method="create" > 
101.        <constructor-arg>  
102.         <props> 
103.                 <prop key="cache.name">mycache</prop> 
104.                 <prop key="cache.cache_policy">LFU</prop> 
105.                 <prop key="cache.cache_storage">memory</prop> 
106.                 <prop key="cache.max_element_count">1000</prop> 
107.                 <prop key="cache.idel_seconds">1</prop> 
108.                 <prop key="cache.live_seconds">2</prop> 
109.             </props> 
110.      </constructor-arg> 
111.     </bean>   
112.      
113.     <bean id="cache2" class="com.cache.Cache" factory-bean="cacheFactory" factory-method="create" > 
114.     </bean>   
115.</pre> 
116.<br>七。测试用例 
117.<br><pre class="java" name="code">public class CacheTest { 
118.     
119.    public static void main(String[] args) throws Exception { 
120.        
121.        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"com/cache/cache.xml"});   
122.        Cache cache1 = (Cache) context.getBean("cache1");   
123.        System.out.println("cache1.name = " + cache1.getName()); 
124.        /*  */  
125.        CacheElement<String,Integer> element = null; 
126.        for(int i = 1 ; i <=4; i++){ 
127.            element = new CacheElement<String,Integer>("key"+i,i); 
128.            cache1.put(element);     
129.        }  
130.        cache1.list(); 
131.        Cache cache2 = (Cache) context.getBean("cache2");   
132.        CacheElement<String,Integer> element2 = null; 
133.        for(int i =5 ; i <=10; i++){ 
134.            element2 = new CacheElement<String,Integer>("key"+i,i); 
135.            cache2.put(element2);    
136.        }  
137.        cache2.list(); 
138.        System.out.println("key1="+cache1.get("key1").getObjectValue());  
139.        System.out.println("key8="+cache2.get("key8").getObjectValue()); 
140.     
141.     } 
142.     
143.  
144.}</pre> 
分享到:
评论

相关推荐

    spring-cache.xsd+spring-encache.xsd

    里面有两个xsd文件,springmodules-ehcache和springmodules-cache.xsd。需求:因为有时候在你在xml中用某个标签时,提示错误,有时候就是少了xsd的引入

    spring-boot-reference.pdf

    15.2. Importing XML Configuration 16. Auto-configuration 16.1. Gradually Replacing Auto-configuration 16.2. Disabling Specific Auto-configuration Classes 17. Spring Beans and Dependency Injection 18. ...

    springmvc和mybatis集成全部jar包(全)

    lib/httpclient-cache-4.2.3.jar lib/httpcore-4.2.2.jar lib/standard-1.1.2.jar lib/pinyin4j-2.5.0.jar lib/log4j-1.2.17.jar lib/jsqlparser-0.9.5.jar lib/kaptcha-2.3.2.jar lib/pagehelper-4.1.6.jar...

    培训体系管理系统-oracle-ssh

    参考用,虽然不咋地,但是有些技能实现的方法可以借鉴。。。上传的lib包中需要加入以下文件,因为容量过大,没有上传,请见谅! antlr-2.7.6.jar antlr-2.7.6rc1.jar aopalliance.jar asm.jar asm-attrs.jar asm-...

    开发用jar包合集

    目前包含jar列表如下: ant-1.9.3.jar ant-launcher-1.9.3.jar asm-all-5.0.3.jar bcpg-jdk15on-1.51.jar bcprov-jdk15on-1.51.jar bndlib-2.1.0.jar bsh-2.0b4.jar ... xml-apis-1.3.04.jar

    spring4.1核心包

    14. spring-oxm-4.1.1.RELEASE.jar Spring对于object/xml映射的支持,可以让JAVA与XML之间来回切换 15. spring-test-4.1.1.RELEASE.jar 支持Spring组建JUnit和TestNG的单元测试和集成测试。 16. spring-tx-4.1.1....

    dubbo、dubbox编译所需jar包

    ant-1.6.2.jar asm-analysis-3.2.jar asm-commons-3.2.jar asm-tree-3.2.jar asm-util-3.2.jar ...xml-im-exporter-1.1.jar xmlParserAPIs-2.6.1.jar xstream-1.4.1.jar zkclient-0.1.jar zookeeper-3.3.3.jar

    Java学习资料-SpringBoot自带模板引擎Thymeleaf使用详解

    - `spring.thymeleaf.cache`:是否启用缓存,默认为 `true`。设置为 `false` 可以禁用缓存。 - `spring.thymeleaf.encoding`:模板文件的编码格式,默认为 `UTF-8`。 - `spring.thymeleaf.mode`:模板模式,可选值为...

    cache-spring-boot-starter:缓存弹簧启动启动器

    缓存弹簧启动启动器 缓存Spring Book Edition 支持功能: 快取 清除缓存 快取: 提供1级JVM缓存和2级Redis缓存可以在集群中使用 ... &lt; artifactId&gt;cache-spring-boot-starter &lt; version&gt;1.1.0-RELEASE &lt;/ depen

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    Praise for the Third Edition of Spring in Action Preface Acknowledgments About this Book 1. Core Spring Chapter 1. Springing into action 1.1. Simplifying Java development 1.1.1. Unleashing the power ...

    (2.0版本)自己写的struts2+hibernate+spring实例

    1.1-beta-7.jar jdbc2_0-stdext.jar jta.jar log4j-1.2.11.jar xerces-2.6.2.jar xml-apis.jar c3p0-0.9.0.jar concurrent-1.3.2.jar connector.jar jboss-cache.jar jboss...

    MyEclipse_9创建SSH2开发环境必须的独立包

    commons-validator.jar 提供了一个简单的,可扩展的框架来在一个XML文件中定义校验器(校验方法)和校验规则 struts2-spring-plugin-2.0.11.2.jar struts2的spring插件 struts2-core-2.0.11.2jar struts2 2.0.11.2的...

    后台管理系统项目课程设计

    2. 修改 spring-cache.xml 文件,配置自己的redis链接 3. 修改 jdbc.properties 文件,配置自己的mysql数据库链接 4. 修改 spring-elasticsearch 文件,配置自己的ElasticSearch集群设置 5. 如果需要自定义一些配置...

    springmvc-ibatis

    &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context=...

    java开发常用jar包

    Xerces是XML解析器,Xalan是格式化器,xml-apis实际上是JAXP。 sitemesh.jar Sitemesh 是一个基于WEB页面的布局、装饰以及应用整合的开源框架。它能帮助我们在由大量页面构成的项目中创建一致的页面布局和外观,...

    web开发常用jar

    web开发常用jar包 常用jar包 commons-beanutils.jar Apache Commons包中的一个,包含了一些Bean工具类类。必须使用的jar包。...Xerces是XML解析器,Xalan是格式化器,xml-apis实际上是JAXP。 sitemesh.jar

    spring-cache-4.2

    配置applicationContext.xml的xsd文件里面.........................................................................

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    - Caching using Spring's cache abstraction - Sending and receiving JMS messages using Spring - Aspect-oriented programming support in Spring - Sending emails using Spring - Asynchronously executing ...

    基于SSH模拟当当网项目(电子商务平台)

    采用Spring+Hibernate方式实现 2.Service改造工作 采用Spring的IoC注入方式使用DAO 3.Action改造工作 采用整合插件注入方式使用Spring容器中的Service或DAO. (默认按名称匹配规则) 4.配置信息的改造 Service和...

    Spring 3.x 中文开发手册.pdf

    Spring 3.x 新特性全部介绍 ...我自己也曾经仿造者,并且基于aspectj山寨过过aop annotation cache 在大部分简单的cache场景都是非常好用的 少部分需要精确evict key的场景还不适合 具体可以参考 ...

Global site tag (gtag.js) - Google Analytics