Memcached之——整合Spring完整示例

Memcached整合Spring的完整示例,好了不多说了,我们直接上代码吧。

一、配置

1、MemcachedCacheManager

  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. }  
package com.cdsmartlink.framework.cache.memcached;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;

import com.danga.MemCached.MemCachedClient;

/**
 * Spring Cache整合Memcached实现 
 * @author liuyazhuang
 */
public class MemcachedCacheManager extends AbstractTransactionSupportingCacheManager {

	private ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>();
	private Map<String, Integer> expireMap = new HashMap<String, Integer>();   //缓存的时间
	private MemCachedClient memcachedClient;   //memcached的客户端

	public MemcachedCacheManager() {
	}

	@Override
	protected Collection<? extends Cache> loadCaches() {
		Collection<Cache> values = cacheMap.values();
		return values;
	}

	@Override
	public Cache getCache(String name) {
		Cache cache = cacheMap.get(name);
		if (cache == null) {
			Integer expire = expireMap.get(name);
			if (expire == null) {
				expire = 0;
				expireMap.put(name, expire);
			}
			cache = new MemcachedCache(name, expire.intValue(), memcachedClient);
			cacheMap.put(name, cache);
		}
		return cache;
	}

	public void setMemcachedClient(MemCachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	public void setConfigMap(Map<String, Integer> configMap) {
		this.expireMap = configMap;
	}

}

2、MemcachedCache

  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. }  
package com.cdsmartlink.framework.cache.memcached;

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

import com.danga.MemCached.MemCachedClient;

/**
 * MemcachedCache的实现,主要实现spring的cache接口
 * @author liuyazhuang
 *
 */
public class MemcachedCache implements Cache {

	private final String name;
	private final MemCache memCache;

	public MemcachedCache(String name, int expire, MemCachedClient memcachedClient) {
		this.name = name;
		this.memCache = new MemCache(name, expire, memcachedClient);
	}

	@Override
	public void clear() {
		memCache.clear();
	}

	@Override
	public void evict(Object key) {
		memCache.delete(key.toString());
	}

	@Override
	public ValueWrapper get(Object key) {
		ValueWrapper wrapper = null;
		Object value = memCache.get(key.toString());
		if (value != null) {
			wrapper = new SimpleValueWrapper(value);
		}
		return wrapper;
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public MemCache getNativeCache() {
		return this.memCache;
	}

	@Override
	public void put(Object key, Object value) {
		memCache.put(key.toString(), value);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T get(Object key, Class<T> type) {
		Object cacheValue = this.memCache.get(key.toString());
		Object value = (cacheValue != null ? cacheValue : null);
		if (type != null && !type.isInstance(value)) {
			throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
		}
		return (T) value;
	}

}

3、MemCache

  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. }  
package com.cdsmartlink.framework.cache.memcached;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.danga.MemCached.MemCachedClient;

/**
 * Memcached的封装类
 * @author liuyazhuang
 *
 */
public class MemCache {
	private static Logger log = LoggerFactory.getLogger(MemCache.class);

	private Set<String> keySet = new HashSet<String>();
	private final String name;
	private final int expire;
	private final MemCachedClient memcachedClient;

	public MemCache(String name, int expire, MemCachedClient memcachedClient) {
		this.name = name;
		this.expire = expire;
		this.memcachedClient = memcachedClient;
	}

	public Object get(String key) {
		Object value = null;
		try {
			key = this.getKey(key);
			value = memcachedClient.get(key);
		} catch (Exception e) {
			log.warn("获取 Memcached 缓存超时", e);
		}
		return value;
	}

	public void put(String key, Object value) {
		if (value == null)
			return;
		try {
			key = this.getKey(key);
			memcachedClient.set(key, value, expire);
			keySet.add(key);
		}catch (Exception e) {
			log.warn("更新 Memcached 缓存错误", e);
		}
	}

	public void clear() {
		for (String key : keySet) {
			try {
				memcachedClient.delete(this.getKey(key));
			}catch (Exception e) {
				log.warn("删除 Memcached 缓存错误", e);
			}
		}
	}

	public void delete(String key) {
		try {
			key = this.getKey(key);
			memcachedClient.delete(key);
		} catch (Exception e) {
			log.warn("删除 Memcached 缓存被中断", e);
		}
	}

	private String getKey(String key) {
		return name + "_" + key;
	}
}

4、applicationContext-memcached.xml

  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>    
<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 						http://www.springframework.org/schema/context 
 						http://www.springframework.org/schema/context/spring-context-3.0.xsd
 						http://www.springframework.org/schema/tx 
 						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 						http://www.springframework.org/schema/aop 
 						http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 						http://www.springframework.org/schema/mvc 
						http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
						http://www.springframework.org/schema/cache 
						http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">

      <!-- 扫描项目包的根路径 -->
    <context:component-scan base-package="com.cdsmartlink" />
    <context:component-scan base-package="com.cdsmartlink.utils.dao.base.impl"/>
    
 	<!-- ===================================  配置Memcached =============================== -->
 	 <!-- 开启缓存 -->  
   <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true" />  
    <!-- 导入外部properties -->
    <context:property-placeholder location="classpath:memcached.properties"/>
    
 	 <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
		factory-method="getInstance" init-method="initialize" destroy-method="shutDown">
	   <constructor-arg>
			<value>neeaMemcachedPool</value>
		</constructor-arg>
		<property name="servers">
			<list>
				<value>${memcache.server}</value>
			</list>
		</property>
		<property name="initConn">
			<value>${memcache.initConn}</value>
		</property>
		<property name="minConn">
			<value>${memcache.minConn}</value>
		</property>
		<property name="maxConn">
			<value>${memcache.maxConn}</value>
		</property>
		<property name="maintSleep">
			<value>${memcache.maintSleep}</value>
		</property>
		<property name="nagle">
			<value>${memcache.nagle}</value>
		</property>
		<property name="socketTO">
			<value>${memcache.socketTO}</value>
		</property>
	</bean>
	
	<!-- 配置MemcachedClient -->
	<bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">
		<constructor-arg>
			<value>neeaMemcachedPool</value>
		</constructor-arg>
	</bean>
	
	<!-- 配置缓存管理 -->
	<bean id="cacheManager" class="com.cdsmartlink.framework.cache.memcached.MemcachedCacheManager">
		<property name="memcachedClient" ref="memcachedClient"/>
		<!-- 配置缓存时间 --> 
		<property name="configMap">
			 <map>
			 	 <!-- key缓存对象名称   value缓存过期时间 --> 
			 	 <entry key="systemCache" value="3600"/>
			 </map>
		</property>
	</bean>
	
 	<!-- 导入调度任务 -->
 	<!-- <import resource="spring-quartz.xml" /> -->
</beans>	

5、memcached.properties

  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   
#Memcached基本配置
memcache.server=192.168.254.120:12000
memcache.initConn=20  
memcache.minConn=10  
memcache.maxConn=50  
memcache.maintSleep=3000  
memcache.nagle=false  
memcache.socketTO=3000 

6、web.xml

  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>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://java.sun.com/xml/ns/javaee" 
		xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
		id="WebApp_ID" version="3.0">
  <display-name>Smartlink</display-name>
  
  <!-- 配置spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	 <!-- 配置初始化监听 -->
    <listener>
        <listener-class>com.cdsmartlink.utils.listener.WebServerStartListener</listener-class>
    </listener>
	
	
	<!-- 加载配置文件路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:applicationContext*.xml</param-value>
	</context-param>
	
	<!-- springmvc配置 -->
	<servlet>
		<servlet-name>smartlink</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>smartlink</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 配置OpenSessionInView -->
	<filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
	
	<filter-mapping>
		<filter-name>hibernateFilter</filter-name>
		<url-pattern>/*</url-pattern>
	 </filter-mapping>
	
	<!-- 字符编码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <error-page>
        <error-code>404</error-code>
        <location>/static/html/page_404/404.html</location>
    </error-page>
</web-app>

二、使用示例

1、CacheBaseService

  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. }  
package com.cdsmartlink.utils.service;

import java.io.Serializable;

/**
 * 带有缓存的service
 * @author liuyazhuang
 *
 * @param <T>
 */
public interface CacheBaseService<T> extends SinglePKBaseService<T>{
	T get(Serializable id);

	void save(T[] entity) ;
	
	void save(T entity) ;
	
	Serializable saveObj(T entity);
	
	void update(T entity) ;

	void delete(T entity) ;
	
	public int delete(Serializable id) ;

	public void delete(Serializable... id) ;
	
}

2、CacheBaseServiceImpl

  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. }  
package com.cdsmartlink.utils.service.impl;

import java.io.Serializable;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;

import com.cdsmartlink.utils.service.CacheBaseService;
public abstract class CacheBaseServiceImpl<T> extends SinglePKBaseServiceImpl<T> implements CacheBaseService<T>{
	
	@Override
	@CachePut(value="systemCache")
	public T get(Serializable id){
		return super.get(id);
	}
	
	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public void save(T[] entity) {
		 super.save(entity);
	}
	
	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public void save(T entity){
		super.save(entity);
	}
	
	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public Serializable saveObj(T entity){
		return super.saveObj(entity);
	}
	
	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public void update(T entity){
		super.update(entity);
	}

	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public void delete(T entity){
		super.delete(entity);
	}
	
	@Override
	@CacheEvict(value="systemCache", beforeInvocation = true)
	public int delete(Serializable id){
		return super.delete(id);
	}

	@Override
	@CacheEvict(value="systemCache", allEntries = true, beforeInvocation = true)
	public void delete(Serializable... id){
		super.delete(id);
	}
}
3、StoreAdvertmentService

  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. }  
package com.cdsmartlink.system.store.service;

import java.util.List;

import com.cdsmartlink.system.store.entity.StoreAdvertment;
import com.cdsmartlink.utils.service.CacheBaseService;

/**
 * 商家广告service
 * @author liuyazhuang
 *
 */
public interface StoreAdvertmentService extends CacheBaseService<StoreAdvertment> {
	
	/**
	 * 缓存key的前缀
	 */
	String STORE_AD = "store_ad_";
	
	/**
	 * 获取广告图
	 * @param storeId
	 * @param type
	 * @param limit
	 * @return
	 */
	List<StoreAdvertment> getStoreAdvertments(Long storeId, Integer type, int limit);
}

4、StoreAdvertmentServiceImpl

  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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值