免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4907 | 回复: 1
打印 上一主题 下一主题

内存缓存接口和实现(采用Ehcache) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-20 11:01 |只看该作者 |倒序浏览
在系统中,采用内存缓存来提供系统的性能。
Cache<K, V>
  1. package com.wms.studio.cache;

  2. import java.util.Collection;
  3. import java.util.Set;

  4. /**
  5. *
  6. * 缓存有效地存储临时对象,以提高一个应用的性能
  7. * 本系统定义一个缓存的接口,用来扩展现有的缓存框架,比如 JCache, Ehcache, JCS, OSCache, JBossCache, TerraCotta, Coherence,
  8. * GigaSpaces等。
  9. *
  10. */
  11. public interface Cache<K, V> {

  12.     /**
  13.      * 获取缓存中指定key下的值,当不存在时,返回为空
  14.      *
  15.      * @param 在设置缓存时指定的key
  16.      * @return 缓存的对象或者为空
  17.      * @throws 当访问出现问题时,抛出CacheException异常
  18.      */
  19.     public V get(K key) throws CacheException;

  20.     /**
  21.      * 添加一个缓存实体
  22.      *
  23.      * @param key   用来标识放入缓存的实体
  24.      * @param value 存放缓存中实体的值
  25.      * @return 返回这个key下,之前存放的实体,当不存在时,返回空
  26.      * @throws 当访问出现问题时,抛出CacheException异常
  27.      */
  28.     public V put(K key, V value) throws CacheException;

  29.     /**
  30.      * 从缓存中,移除指定key的实体
  31.      *
  32.      * @param 在添加缓存时设置的key
  33.      * @return 返回这个key下,之前存放的实体,当不存在时,返回空
  34.      * @throws 当访问出现问题时,抛出CacheException异常
  35.      */
  36.     public V remove(K key) throws CacheException;

  37.     /**
  38.      * 清空缓存
  39.      *
  40.      * @throws 当访问出现问题时,抛出CacheException异常
  41.      */
  42.     public void clear() throws CacheException;

  43.     /**
  44.      * 返回在缓存中,存放实体的个数
  45.      *
  46.      * @return 在缓存中,存放实体的个数
  47.      */
  48.     public int size();

  49.     /**
  50.      * 返回缓存中所有实体的key
  51.      *
  52.      * @return 缓存中所有实体的key
  53.      */
  54.     public Set<K> keys();

  55.     /**
  56.      * 返回在缓存中,存放的所有实体
  57.      *
  58.      * @return 在缓存中,存放的所有实体
  59.      */
  60.     public Collection<V> values();
  61. }
复制代码
CacheException
  1. /**
  2. *  Copyright 2015 WMS(560130911@163.com)
  3. *  
  4. *  Licensed under the Apache License, Version 2.0 (the "License");
  5. *  you may not use this file except in compliance with the License.
  6. *  You may obtain a copy of the License at
  7. *  
  8. *      http://www.apache.org/licenses/LICENSE-2.0
  9. *  Unless required by applicable law or agreed to in writing, software
  10. *  distributed under the License is distributed on an "AS IS" BASIS,
  11. *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. *  See the License for the specific language governing permissions and
  13. *  limitations under the License.
  14. */
  15. package com.wms.studio.cache;

  16. /**
  17. * @author WMS
  18. * @date 2015年7月18日-下午8:57:03
  19. * @version 1.0
  20. */
  21. @SuppressWarnings("serial")
  22. public class CacheException extends RuntimeException {

  23.     /**
  24.      * 创建一个新的 <code>CacheException</code>.
  25.      */
  26.     public CacheException() {
  27.         super();
  28.     }

  29.     /**
  30.      * 创建一个新的 <code>CacheException</code>.
  31.      *
  32.      * @param message
  33.      *            抛出异常的原因.
  34.      */
  35.     public CacheException(String message) {
  36.         super(message);
  37.     }

  38.     /**
  39.      * 创建一个新的 <code>CacheException</code>.
  40.      *
  41.      * @param cause
  42.      *            抛出异常的底层原因.
  43.      */
  44.     public CacheException(Throwable cause) {
  45.         super(cause);
  46.     }

  47.     /**
  48.      * 创建一个新的 <code>CacheException</code>.
  49.      *
  50.      * @param message
  51.      *            抛出异常的原因.
  52.      * @param cause
  53.      *            抛出异常的底层原因.
  54.      */
  55.     public CacheException(String message, Throwable cause) {
  56.         super(message, cause);
  57.     }
  58. }
复制代码
CacheManager
  1. /**
  2. *  Copyright 2015 WMS(560130911@163.com)
  3. *  
  4. *  Licensed under the Apache License, Version 2.0 (the "License");
  5. *  you may not use this file except in compliance with the License.
  6. *  You may obtain a copy of the License at
  7. *  
  8. *      http://www.apache.org/licenses/LICENSE-2.0
  9. *  Unless required by applicable law or agreed to in writing, software
  10. *  distributed under the License is distributed on an "AS IS" BASIS,
  11. *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. *  See the License for the specific language governing permissions and
  13. *  limitations under the License.
  14. */
  15. package com.wms.studio.cache;


  16. /**
  17. * @author WMS
  18. * @date 2015年7月18日-下午9:03:19
  19. * @version 1.0
  20. */
  21. public interface CacheManager {

  22.      /**
  23.       * 获取指定名称的缓存,当这个缓存不存在时,将会创建一个缓存并返回。
  24.      *
  25.      * @param name 需要获取缓存的名称
  26.      * @return 指定名称的缓存
  27.      * @throws 当访问出现问题时,抛出CacheException异常
  28.      */
  29.     public <K, V> Cache<K, V> getCache(String name) throws CacheException;
  30. }
复制代码
EhCache
  1. package com.wms.studio.cache;

  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.Collections;
  5. import java.util.LinkedHashSet;
  6. import java.util.List;
  7. import java.util.Set;

  8. import net.sf.ehcache.Element;

  9. import org.apache.commons.collections.CollectionUtils;
  10. import org.apache.log4j.Logger;

  11. public class EhCache<K, V> implements Cache<K, V> {

  12.     /**
  13.      * 私有的内部日志实例
  14.      */
  15.     private static final Logger log = Logger.getLogger(EhCache.class);

  16.     /**
  17.      * 包裹的Ehcache实例
  18.      */
  19.     private net.sf.ehcache.Ehcache cache;

  20.     /**
  21.      *
  22.      * 使用指定net.sf.ehcache.Ehcache的实例构建一个新的EhCache实例
  23.      *
  24.      * @param cache - net.sf.ehcache.Ehcache实例
  25.      */
  26.     public EhCache(net.sf.ehcache.Ehcache cache) {
  27.         if (cache == null) {
  28.             throw new IllegalArgumentException("缓存参数不允许为空.");
  29.         }
  30.         this.cache = cache;
  31.     }

  32.     /**
  33.      * 获取指定key下的元素
  34.      *
  35.      * @param key the key of the element to return.
  36.      * @return The value placed into the cache with an earlier put, or null if not found or expired
  37.      */
  38.     @SuppressWarnings("unchecked")
  39.     public V get(K key) throws CacheException {
  40.         try {
  41.             if (log.isTraceEnabled()) {
  42.                 log.trace("Getting object from cache [" + cache.getName() + "] for key [" + key + "]");
  43.             }
  44.             if (key == null) {
  45.                 return null;
  46.             } else {
  47.                 Element element = cache.get(key);
  48.                 if (element == null) {
  49.                     if (log.isTraceEnabled()) {
  50.                         log.trace("Element for [" + key + "] is null.");
  51.                     }
  52.                     return null;
  53.                 } else {
  54.                     //noinspection unchecked
  55.                     return (V) element.getObjectValue();
  56.                 }
  57.             }
  58.         } catch (Throwable t) {
  59.             throw new CacheException(t);
  60.         }
  61.     }

  62.     /**
  63.      * Puts an object into the cache.
  64.      *
  65.      * @param key   the key.
  66.      * @param value the value.
  67.      */
  68.     public V put(K key, V value) throws CacheException {
  69.         if (log.isTraceEnabled()) {
  70.             log.trace("Putting object in cache [" + cache.getName() + "] for key [" + key + "]");
  71.         }
  72.         try {
  73.             V previous = get(key);
  74.             Element element = new Element(key, value);
  75.             cache.put(element);
  76.             return previous;
  77.         } catch (Throwable t) {
  78.             throw new CacheException(t);
  79.         }
  80.     }

  81.     /**
  82.      * Removes the element which matches the key.
  83.      *
  84.      * <p>If no element matches, nothing is removed and no Exception is thrown.</p>
  85.      *
  86.      * @param key the key of the element to remove
  87.      */
  88.     public V remove(K key) throws CacheException {
  89.         if (log.isTraceEnabled()) {
  90.             log.trace("Removing object from cache [" + cache.getName() + "] for key [" + key + "]");
  91.         }
  92.         try {
  93.             V previous = get(key);
  94.             cache.remove(key);
  95.             return previous;
  96.         } catch (Throwable t) {
  97.             throw new CacheException(t);
  98.         }
  99.     }

  100.     /**
  101.      * Removes all elements in the cache, but leaves the cache in a useable state.
  102.      */
  103.     public void clear() throws CacheException {
  104.         if (log.isTraceEnabled()) {
  105.             log.trace("Clearing all objects from cache [" + cache.getName() + "]");
  106.         }
  107.         try {
  108.             cache.removeAll();
  109.         } catch (Throwable t) {
  110.             throw new CacheException(t);
  111.         }
  112.     }

  113.     public int size() {
  114.         try {
  115.             return cache.getSize();
  116.         } catch (Throwable t) {
  117.             throw new CacheException(t);
  118.         }
  119.     }

  120.     public Set<K> keys() {
  121.         try {
  122.             @SuppressWarnings({"unchecked"})
  123.             List<K> keys = cache.getKeys();
  124.             if (!CollectionUtils.isEmpty(keys)) {
  125.                 return Collections.unmodifiableSet(new LinkedHashSet<K>(keys));
  126.             } else {
  127.                 return Collections.emptySet();
  128.             }
  129.         } catch (Throwable t) {
  130.             throw new CacheException(t);
  131.         }
  132.     }

  133.     public Collection<V> values() {
  134.         try {
  135.             @SuppressWarnings({"unchecked"})
  136.             List<K> keys = cache.getKeys();
  137.             if (!CollectionUtils.isEmpty(keys)) {
  138.                 List<V> values = new ArrayList<V>(keys.size());
  139.                 for (K key : keys) {
  140.                     V value = get(key);
  141.                     if (value != null) {
  142.                         values.add(value);
  143.                     }
  144.                 }
  145.                 return Collections.unmodifiableList(values);
  146.             } else {
  147.                 return Collections.emptyList();
  148.             }
  149.         } catch (Throwable t) {
  150.             throw new CacheException(t);
  151.         }
  152.     }

  153.     /**
  154.      * Returns the size (in bytes) that this EhCache is using in memory (RAM), or <code>-1</code> if that
  155.      * number is unknown or cannot be calculated.
  156.      *
  157.      * @return the size (in bytes) that this EhCache is using in memory (RAM), or <code>-1</code> if that
  158.      *         number is unknown or cannot be calculated.
  159.      */
  160.     public long getMemoryUsage() {
  161.         try {
  162.             return cache.calculateInMemorySize();
  163.         }
  164.         catch (Throwable t) {
  165.             return -1;
  166.         }
  167.     }

  168.     /**
  169.      * Returns the size (in bytes) that this EhCache's memory store is using (RAM), or <code>-1</code> if
  170.      * that number is unknown or cannot be calculated.
  171.      *
  172.      * @return the size (in bytes) that this EhCache's memory store is using (RAM), or <code>-1</code> if
  173.      *         that number is unknown or cannot be calculated.
  174.      */
  175.     public long getMemoryStoreSize() {
  176.         try {
  177.             return cache.getMemoryStoreSize();
  178.         }
  179.         catch (Throwable t) {
  180.             throw new CacheException(t);
  181.         }
  182.     }

  183.     /**
  184.      * Returns the size (in bytes) that this EhCache's disk store is consuming or <code>-1</code> if
  185.      * that number is unknown or cannot be calculated.
  186.      *
  187.      * @return the size (in bytes) that this EhCache's disk store is consuming or <code>-1</code> if
  188.      *         that number is unknown or cannot be calculated.
  189.      */
  190.     public long getDiskStoreSize() {
  191.         try {
  192.             return cache.getDiskStoreSize();
  193.         } catch (Throwable t) {
  194.             throw new CacheException(t);
  195.         }
  196.     }

  197.     /**
  198.      * Returns &quot;EhCache [&quot; + cache.getName() + &quot;]&quot;
  199.      *
  200.      * @return &quot;EhCache [&quot; + cache.getName() + &quot;]&quot;
  201.      */
  202.     public String toString() {
  203.         return "EhCache [" + cache.getName() + "]";
  204.     }
  205. }
复制代码
EhCacheManager
  1. package com.wms.studio.cache;

  2. import net.sf.ehcache.config.Configuration;
  3. import net.sf.ehcache.config.ConfigurationFactory;

  4. import org.apache.log4j.Logger;
  5. import org.springframework.beans.factory.DisposableBean;
  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.cache.ehcache.EhCacheManagerUtils;
  8. import org.springframework.core.io.Resource;

  9. public class EhCacheManager implements CacheManager, InitializingBean,
  10.         DisposableBean {

  11.     /**
  12.      * This class's private log instance.
  13.      */
  14.     private static final Logger log = Logger.getLogger(EhCacheManager.class);

  15.     /**
  16.      * The EhCache cache manager used by this implementation to create caches.
  17.      */
  18.     protected net.sf.ehcache.CacheManager manager;

  19.     /**
  20.      * Indicates if the CacheManager instance was implicitly/automatically
  21.      * created by this instance, indicating that it should be automatically
  22.      * cleaned up as well on shutdown.
  23.      */
  24.     private boolean cacheManagerImplicitlyCreated = false;

  25.     private Resource configLocation;

  26.     /**
  27.      * Default no argument constructor
  28.      */
  29.     public EhCacheManager() {
  30.     }

  31.     /**
  32.      * Returns the wrapped Ehcache {@link net.sf.ehcache.CacheManager
  33.      * CacheManager} instance.
  34.      *
  35.      * @return the wrapped Ehcache {@link net.sf.ehcache.CacheManager
  36.      *         CacheManager} instance.
  37.      */
  38.     public net.sf.ehcache.CacheManager getCacheManager() {
  39.         return manager;
  40.     }

  41.     /**
  42.      * Sets the wrapped Ehcache {@link net.sf.ehcache.CacheManager CacheManager}
  43.      * instance.
  44.      *
  45.      * @param manager
  46.      *            the wrapped Ehcache {@link net.sf.ehcache.CacheManager
  47.      *            CacheManager} instance.
  48.      */
  49.     public void setCacheManager(net.sf.ehcache.CacheManager manager) {
  50.         this.manager = manager;
  51.     }

  52.     /**
  53.      * @param configLocation
  54.      *            the configLocation to set
  55.      */
  56.     public void setConfigLocation(Resource configLocation) {
  57.         this.configLocation = configLocation;
  58.     }

  59.     /**
  60.      * Loads an existing EhCache from the cache manager, or starts a new cache
  61.      * if one is not found.
  62.      *
  63.      * @param name
  64.      *            the name of the cache to load/create.
  65.      */
  66.     public final <K, V> Cache<K, V> getCache(String name) throws CacheException {

  67.         if (log.isTraceEnabled()) {
  68.             log.trace("Acquiring EhCache instance named [" + name + "]");
  69.         }

  70.         try {
  71.             net.sf.ehcache.Ehcache cache = this.manager
  72.                     .getEhcache(name);
  73.             if (cache == null) {
  74.                 if (log.isInfoEnabled()) {
  75.                     log.info("Cache with name " + name
  76.                             + " does not yet exist.  Creating now."

  77.                     );
  78.                 }
  79.                 this.manager.addCache(name);

  80.                 cache = manager.getCache(name);

  81.                 if (log.isInfoEnabled()) {
  82.                     log.info("Added EhCache named [" + name + "]");
  83.                 }
  84.             } else {
  85.                 if (log.isInfoEnabled()) {
  86.                     log.info("Using existing EHCache named [" + cache.getName()
  87.                             + "]");
  88.                 }
  89.             }
  90.             return new EhCache<K, V>(cache);
  91.         } catch (net.sf.ehcache.CacheException e) {
  92.             throw new CacheException(e);
  93.         }
  94.     }


  95.     /**
  96.      * Shuts-down the wrapped Ehcache CacheManager <b>only if implicitly
  97.      * created</b>.
  98.      * <p/>
  99.      * If another component injected a non-null CacheManager into this instace
  100.      * before calling {@link #init() init}, this instance expects that same
  101.      * component to also destroy the CacheManager instance, and it will not
  102.      * attempt to do so.
  103.      */
  104.     public void destroy() {
  105.         if (cacheManagerImplicitlyCreated) {
  106.             try {
  107.                 net.sf.ehcache.CacheManager cacheMgr = getCacheManager();
  108.                 cacheMgr.shutdown();
  109.             } catch (Exception e) {
  110.                 log.warn("Unable to cleanly shutdown implicitly created CacheManager instance.  "
  111.                         + "Ignoring (shutting down)...");
  112.             }
  113.             cacheManagerImplicitlyCreated = false;
  114.         }
  115.     }

  116.     public void afterPropertiesSet() throws Exception {
  117.         try {
  118.             if (this.manager == null) {
  119.                 if (log.isDebugEnabled()) {
  120.                     log.debug("cacheManager property not set.  Constructing CacheManager instance... ");
  121.                 }
  122.                 Configuration configuration = (this.configLocation != null ? EhCacheManagerUtils
  123.                         .parseConfiguration(this.configLocation)
  124.                         : ConfigurationFactory.parseConfiguration());
  125.                 this.manager = new net.sf.ehcache.CacheManager(configuration);
  126.                 if (log.isTraceEnabled()) {
  127.                     log.trace("instantiated Ehcache CacheManager instance.");
  128.                 }
  129.                 cacheManagerImplicitlyCreated = true;
  130.                 if (log.isDebugEnabled()) {
  131.                     log.debug("implicit cacheManager created successfully.");
  132.                 }
  133.             }
  134.         } catch (Exception e) {
  135.             throw new CacheException(e);
  136.         }
  137.          
  138.     }

  139. }
复制代码

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
2 [报告]
发表于 2015-08-12 11:47 |只看该作者
会造成内在泄露不。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP