Spring整合Memcached的完整示例

转载:http://blog.csdn.net/l1028386804/article/details/48464111

在前面的几篇博文中,我们记录了Memcached整合Spring的一些方法,现在我们就基于这些方法实现一个Memcached整合Spring的完整示例,好了不多说了,我们直接上代码吧。

一、配置

1、MemcachedCacheManager

[java]  view plain  copy
  1. package com.cdsmartlink.framework.cache.memcached;  
  2.   
  3. import java.util.Collection;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6. import java.util.concurrent.ConcurrentHashMap;  
  7. import java.util.concurrent.ConcurrentMap;  
  8.   
  9. import org.springframework.cache.Cache;  
  10. import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;  
  11.   
  12. import com.danga.MemCached.MemCachedClient;  
  13.   
  14. /** 
  15.  * Spring Cache整合Memcached实现  
  16.  * @author liuyazhuang 
  17.  */  
  18. public class MemcachedCacheManager extends AbstractTransactionSupportingCacheManager {  
  19.   
  20.     private ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>();  
  21.     private Map<String, Integer> expireMap = new HashMap<String, Integer>();   //缓存的时间  
  22.     private MemCachedClient memcachedClient;   //memcached的客户端  
  23.   
  24.     public MemcachedCacheManager() {  
  25.     }  
  26.   
  27.     @Override  
  28.     protected Collection<? extends Cache> loadCaches() {  
  29.         Collection<Cache> values = cacheMap.values();  
  30.         return values;  
  31.     }  
  32.   
  33.     @Override  
  34.     public Cache getCache(String name) {  
  35.         Cache cache = cacheMap.get(name);  
  36.         if (cache == null) {  
  37.             Integer expire = expireMap.get(name);  
  38.             if (expire == null) {  
  39.                 expire = 0;  
  40.                 expireMap.put(name, expire);  
  41.             }  
  42.             cache = new MemcachedCache(name, expire.intValue(), memcachedClient);  
  43.             cacheMap.put(name, cache);  
  44.         }  
  45.         return cache;  
  46.     }  
  47.   
  48.     public void setMemcachedClient(MemCachedClient memcachedClient) {  
  49.         this.memcachedClient = memcachedClient;  
  50.     }  
  51.   
  52.     public void setConfigMap(Map<String, Integer> configMap) {  
  53.         this.expireMap = configMap;  
  54.     }  
  55.   
  56. }  

2、MemcachedCache

[java]  view plain  copy
  1. package com.cdsmartlink.framework.cache.memcached;  
  2.   
  3. import org.springframework.cache.Cache;  
  4. import org.springframework.cache.support.SimpleValueWrapper;  
  5.   
  6. import com.danga.MemCached.MemCachedClient;  
  7.   
  8. /** 
  9.  * MemcachedCache的实现,主要实现spring的cache接口 
  10.  * @author liuyazhuang 
  11.  * 
  12.  */  
  13. public class MemcachedCache implements Cache {  
  14.   
  15.     private final String name;  
  16.     private final MemCache memCache;  
  17.   
  18.     public MemcachedCache(String name, int expire, MemCachedClient memcachedClient) {  
  19.         this.name = name;  
  20.         this.memCache = new MemCache(name, expire, memcachedClient);  
  21.     }  
  22.   
  23.     @Override  
  24.     public void clear() {  
  25.         memCache.clear();  
  26.     }  
  27.   
  28.     @Override  
  29.     public void evict(Object key) {  
  30.         memCache.delete(key.toString());  
  31.     }  
  32.   
  33.     @Override  
  34.     public ValueWrapper get(Object key) {  
  35.         ValueWrapper wrapper = null;  
  36.         Object value = memCache.get(key.toString());  
  37.         if (value != null) {  
  38.             wrapper = new SimpleValueWrapper(value);  
  39.         }  
  40.         return wrapper;  
  41.     }  
  42.   
  43.     @Override  
  44.     public String getName() {  
  45.         return this.name;  
  46.     }  
  47.   
  48.     @Override  
  49.     public MemCache getNativeCache() {  
  50.         return this.memCache;  
  51.     }  
  52.   
  53.     @Override  
  54.     public void put(Object key, Object value) {  
  55.         memCache.put(key.toString(), value);  
  56.     }  
  57.   
  58.     @Override  
  59.     @SuppressWarnings("unchecked")  
  60.     public <T> T get(Object key, Class<T> type) {  
  61.         Object cacheValue = this.memCache.get(key.toString());  
  62.         Object value = (cacheValue != null ? cacheValue : null);  
  63.         if (type != null && !type.isInstance(value)) {  
  64.             throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);  
  65.         }  
  66.         return (T) value;  
  67.     }  
  68.   
  69. }  

3、MemCache

[java]  view plain  copy
  1. package com.cdsmartlink.framework.cache.memcached;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8.   
  9. import com.danga.MemCached.MemCachedClient;  
  10.   
  11. /** 
  12.  * Memcached的封装类 
  13.  * @author liuyazhuang 
  14.  * 
  15.  */  
  16. public class MemCache {  
  17.     private static Logger log = LoggerFactory.getLogger(MemCache.class);  
  18.   
  19.     private Set<String> keySet = new HashSet<String>();  
  20.     private final String name;  
  21.     private final int expire;  
  22.     private final MemCachedClient memcachedClient;  
  23.   
  24.     public MemCache(String name, int expire, MemCachedClient memcachedClient) {  
  25.         this.name = name;  
  26.         this.expire = expire;  
  27.         this.memcachedClient = memcachedClient;  
  28.     }  
  29.   
  30.     public Object get(String key) {  
  31.         Object value = null;  
  32.         try {  
  33.             key = this.getKey(key);  
  34.             value = memcachedClient.get(key);  
  35.         } catch (Exception e) {  
  36.             log.warn("获取 Memcached 缓存超时", e);  
  37.         }  
  38.         return value;  
  39.     }  
  40.   
  41.     public void put(String key, Object value) {  
  42.         if (value == null)  
  43.             return;  
  44.         try {  
  45.             key = this.getKey(key);  
  46.             memcachedClient.set(key, value, expire);  
  47.             keySet.add(key);  
  48.         }catch (Exception e) {  
  49.             log.warn("更新 Memcached 缓存错误", e);  
  50.         }  
  51.     }  
  52.   
  53.     public void clear() {  
  54.         for (String key : keySet) {  
  55.             try {  
  56.                 memcachedClient.delete(this.getKey(key));  
  57.             }catch (Exception e) {  
  58.                 log.warn("删除 Memcached 缓存错误", e);  
  59.             }  
  60.         }  
  61.     }  
  62.   
  63.     public void delete(String key) {  
  64.         try {  
  65.             key = this.getKey(key);  
  66.             memcachedClient.delete(key);  
  67.         } catch (Exception e) {  
  68.             log.warn("删除 Memcached 缓存被中断", e);  
  69.         }  
  70.     }  
  71.   
  72.     private String getKey(String key) {  
  73.         return name + "_" + key;  
  74.     }  
  75. }  

4、applicationContext-memcached.xml

[html]  view plain  copy
  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"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xmlns:aop="http://www.springframework.org/schema/aop"   
  7.        xmlns:tx="http://www.springframework.org/schema/tx"  
  8.        xmlns:mvc="http://www.springframework.org/schema/mvc"  
  9.        xmlns:cache="http://www.springframework.org/schema/cache"  
  10.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  11.                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  12.                         http://www.springframework.org/schema/context   
  13.                         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  14.                         http://www.springframework.org/schema/tx   
  15.                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  16.                         http://www.springframework.org/schema/aop   
  17.                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  18.                         http://www.springframework.org/schema/mvc   
  19.                         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  20.                         http://www.springframework.org/schema/cache   
  21.                         http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">  
  22.   
  23.       <!-- 扫描项目包的根路径 -->  
  24.     <context:component-scan base-package="com.cdsmartlink" />  
  25.     <context:component-scan base-package="com.cdsmartlink.utils.dao.base.impl"/>  
  26.       
  27.     <!-- ===================================  配置Memcached =============================== -->  
  28.      <!-- 开启缓存 -->    
  29.    <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true" />    
  30.     <!-- 导入外部properties -->  
  31.     <context:property-placeholder location="classpath:memcached.properties"/>  
  32.       
  33.      <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"  
  34.         factory-method="getInstance" init-method="initialize" destroy-method="shutDown">  
  35.        <constructor-arg>  
  36.             <value>neeaMemcachedPool</value>  
  37.         </constructor-arg>  
  38.         <property name="servers">  
  39.             <list>  
  40.                 <value>${memcache.server}</value>  
  41.             </list>  
  42.         </property>  
  43.         <property name="initConn">  
  44.             <value>${memcache.initConn}</value>  
  45.         </property>  
  46.         <property name="minConn">  
  47.             <value>${memcache.minConn}</value>  
  48.         </property>  
  49.         <property name="maxConn">  
  50.             <value>${memcache.maxConn}</value>  
  51.         </property>  
  52.         <property name="maintSleep">  
  53.             <value>${memcache.maintSleep}</value>  
  54.         </property>  
  55.         <property name="nagle">  
  56.             <value>${memcache.nagle}</value>  
  57.         </property>  
  58.         <property name="socketTO">  
  59.             <value>${memcache.socketTO}</value>  
  60.         </property>  
  61.     </bean>  
  62.       
  63.     <!-- 配置MemcachedClient -->  
  64.     <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">  
  65.         <constructor-arg>  
  66.             <value>neeaMemcachedPool</value>  
  67.         </constructor-arg>  
  68.     </bean>  
  69.       
  70.     <!-- 配置缓存管理 -->  
  71.     <bean id="cacheManager" class="com.cdsmartlink.framework.cache.memcached.MemcachedCacheManager">  
  72.         <property name="memcachedClient" ref="memcachedClient"/>  
  73.         <!-- 配置缓存时间 -->   
  74.         <property name="configMap">  
  75.              <map>  
  76.                  <!-- key缓存对象名称   value缓存过期时间 -->   
  77.                  <entry key="systemCache" value="3600"/>  
  78.              </map>  
  79.         </property>  
  80.     </bean>  
  81.       
  82.     <!-- 导入调度任务 -->  
  83.     <!-- <import resource="spring-quartz.xml" /> -->  
  84. </beans>    

5、memcached.properties

[plain]  view plain  copy
  1. #Memcached基本配置  
  2. memcache.server=192.168.254.120:12000  
  3. memcache.initConn=20    
  4. memcache.minConn=10    
  5. memcache.maxConn=50    
  6. memcache.maintSleep=3000    
  7. memcache.nagle=false    
  8. memcache.socketTO=3000   

6、web.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.         xmlns="http://java.sun.com/xml/ns/javaee"   
  4.         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
  5.         id="WebApp_ID" version="3.0">  
  6.   <display-name>Smartlink</display-name>  
  7.     
  8.   <!-- 配置spring监听器 -->  
  9.     <listener>  
  10.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  11.     </listener>  
  12.       
  13.      <!-- 配置初始化监听 -->  
  14.     <listener>  
  15.         <listener-class>com.cdsmartlink.utils.listener.WebServerStartListener</listener-class>  
  16.     </listener>  
  17.       
  18.       
  19.     <!-- 加载配置文件路径 -->  
  20.     <context-param>  
  21.         <param-name>contextConfigLocation</param-name>  
  22.         <param-value>classpath*:applicationContext*.xml</param-value>  
  23.     </context-param>  
  24.       
  25.     <!-- springmvc配置 -->  
  26.     <servlet>  
  27.         <servlet-name>smartlink</servlet-name>  
  28.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  29.         <load-on-startup>1</load-on-startup>  
  30.     </servlet>  
  31.     <servlet-mapping>  
  32.         <servlet-name>smartlink</servlet-name>  
  33.         <url-pattern>/</url-pattern>  
  34.     </servlet-mapping>  
  35.       
  36.     <!-- 配置OpenSessionInView -->  
  37.     <filter>  
  38.         <filter-name>hibernateFilter</filter-name>  
  39.         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  40.         <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->  
  41.         <init-param>  
  42.             <param-name>singleSession</param-name>  
  43.             <param-value>true</param-value>  
  44.         </init-param>  
  45.     </filter>  
  46.       
  47.     <filter-mapping>  
  48.         <filter-name>hibernateFilter</filter-name>  
  49.         <url-pattern>/*</url-pattern>  
  50.      </filter-mapping>  
  51.       
  52.     <!-- 字符编码过滤器 -->  
  53.     <filter>  
  54.         <filter-name>CharacterEncodingFilter</filter-name>  
  55.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  56.         <init-param>  
  57.             <param-name>encoding</param-name>  
  58.             <param-value>UTF-8</param-value>  
  59.         </init-param>  
  60.         <init-param>  
  61.             <param-name>forceEncoding</param-name>  
  62.             <param-value>true</param-value>  
  63.         </init-param>  
  64.     </filter>  
  65.     <filter-mapping>  
  66.         <filter-name>CharacterEncodingFilter</filter-name>  
  67.         <url-pattern>/*</url-pattern>  
  68.     </filter-mapping>  
  69.        
  70.   <welcome-file-list>  
  71.     <welcome-file>index.html</welcome-file>  
  72.     <welcome-file>index.htm</welcome-file>  
  73.     <welcome-file>index.jsp</welcome-file>  
  74.     <welcome-file>default.html</welcome-file>  
  75.     <welcome-file>default.htm</welcome-file>  
  76.     <welcome-file>default.jsp</welcome-file>  
  77.   </welcome-file-list>  
  78.     
  79.    <error-page>  
  80.         <error-code>404</error-code>  
  81.         <location>/static/html/page_404/404.html</location>  
  82.     </error-page>  
  83. </web-app>  

二、使用示例

1、CacheBaseService

[java]  view plain  copy
  1. package com.cdsmartlink.utils.service;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. /** 
  6.  * 带有缓存的service 
  7.  * @author liuyazhuang 
  8.  * 
  9.  * @param <T> 
  10.  */  
  11. public interface CacheBaseService<T> extends SinglePKBaseService<T>{  
  12.     T get(Serializable id);  
  13.   
  14.     void save(T[] entity) ;  
  15.       
  16.     void save(T entity) ;  
  17.       
  18.     Serializable saveObj(T entity);  
  19.       
  20.     void update(T entity) ;  
  21.   
  22.     void delete(T entity) ;  
  23.       
  24.     public int delete(Serializable id) ;  
  25.   
  26.     public void delete(Serializable... id) ;  
  27.       
  28. }  

2、CacheBaseServiceImpl

[java]  view plain  copy
  1. package com.cdsmartlink.utils.service.impl;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import org.springframework.cache.annotation.CacheEvict;  
  6. import org.springframework.cache.annotation.CachePut;  
  7.   
  8. import com.cdsmartlink.utils.service.CacheBaseService;  
  9. public abstract class CacheBaseServiceImpl<T> extends SinglePKBaseServiceImpl<T> implements CacheBaseService<T>{  
  10.       
  11.     @Override  
  12.     @CachePut(value="systemCache")  
  13.     public T get(Serializable id){  
  14.         return super.get(id);  
  15.     }  
  16.       
  17.     @Override  
  18.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  19.     public void save(T[] entity) {  
  20.          super.save(entity);  
  21.     }  
  22.       
  23.     @Override  
  24.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  25.     public void save(T entity){  
  26.         super.save(entity);  
  27.     }  
  28.       
  29.     @Override  
  30.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  31.     public Serializable saveObj(T entity){  
  32.         return super.saveObj(entity);  
  33.     }  
  34.       
  35.     @Override  
  36.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  37.     public void update(T entity){  
  38.         super.update(entity);  
  39.     }  
  40.   
  41.     @Override  
  42.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  43.     public void delete(T entity){  
  44.         super.delete(entity);  
  45.     }  
  46.       
  47.     @Override  
  48.     @CacheEvict(value="systemCache", beforeInvocation = true)  
  49.     public int delete(Serializable id){  
  50.         return super.delete(id);  
  51.     }  
  52.   
  53.     @Override  
  54.     @CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)  
  55.     public void delete(Serializable... id){  
  56.         super.delete(id);  
  57.     }  
  58. }  

3、StoreAdvertmentService

[java]  view plain  copy
  1. package com.cdsmartlink.system.store.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.cdsmartlink.system.store.entity.StoreAdvertment;  
  6. import com.cdsmartlink.utils.service.CacheBaseService;  
  7.   
  8. /** 
  9.  * 商家广告service 
  10.  * @author liuyazhuang 
  11.  * 
  12.  */  
  13. public interface StoreAdvertmentService extends CacheBaseService<StoreAdvertment> {  
  14.       
  15.     /** 
  16.      * 缓存key的前缀 
  17.      */  
  18.     String STORE_AD = "store_ad_";  
  19.       
  20.     /** 
  21.      * 获取广告图 
  22.      * @param storeId 
  23.      * @param type 
  24.      * @param limit 
  25.      * @return 
  26.      */  
  27.     List<StoreAdvertment> getStoreAdvertments(Long storeId, Integer type, int limit);  
  28. }  

4、StoreAdvertmentServiceImpl

[java]  view plain  copy
  1. package com.cdsmartlink.system.store.service.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.cache.annotation.Cacheable;  
  8. import org.springframework.stereotype.Service;  
  9.   
  10. import com.cdsmartlink.system.store.dao.StoreAdvertmentDao;  
  11. import com.cdsmartlink.system.store.entity.StoreAdvertment;  
  12. import com.cdsmartlink.system.store.service.StoreAdvertmentService;  
  13. import com.cdsmartlink.utils.dao.QueryMode;  
  14. import com.cdsmartlink.utils.dao.QueryParse;  
  15. import com.cdsmartlink.utils.dao.base.BaseDao;  
  16. import com.cdsmartlink.utils.service.impl.CacheBaseServiceImpl;  
  17. @Service  
  18. public class StoreAdvertmentServiceImpl extends CacheBaseServiceImpl<StoreAdvertment> implements  
  19.         StoreAdvertmentService {  
  20.     @Resource  
  21.     private StoreAdvertmentDao storeAdvertmentDao;  
  22.     @Override  
  23.     protected BaseDao<StoreAdvertment> getDao() {  
  24.         return storeAdvertmentDao;  
  25.     }  
  26.   
  27.     @Override  
  28.     protected void setQueryParse(QueryParse<StoreAdvertment> qp,  
  29.             QueryMode queryMode) {  
  30.           
  31.     }  
  32.   
  33.     @Override  
  34.     @Cacheable(value=SYSTEM_CACHE, key="'store_ad_'+ #storeId")//store_ad_为key的自定义字符串前缀,这个前缀可以根据具体业务设定,以免和其他缓存数据冲突,注意,这个字符串前缀要用单引号''括起来,否则会报错  
  35.     public List<StoreAdvertment> getStoreAdvertments(Long storeId, Integer type, int limit) {  
  36.         return storeAdvertmentDao.getStoreAdvertments(storeId, type, limit);  
  37.     }  
  38.   
  39. }  

猜你喜欢

转载自blog.csdn.net/u011109589/article/details/80569935