運行環境:spring3.2.1 + simple-spring-memcached3.1.0(如下簡稱SSM)css
1. 所需jar包,spring的包到spring官網下載,ssm所需包在這裏下載,我下載的是3.1.0版本java
注:解壓simple-spring-memcached-3.1.0-dist.zip,複製lib目錄中全部jar到工程lib 中,若是有相同的jar,保留版本高的,刪除版本低的。複製dist目錄中除了帶有test的以外全部jar到工程的lib中。最終lib包以下:web
2. 配置項目的web.xml文件,由於本人項目用的是spring-mvc,因此代碼以下:spring
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3.0.xsd" id="WebApp_ID" > <!-- ############################################################################## --> <!-- 字符集過濾器 --> <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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- ############################################################################## --> <!-- spring-mvc 控制器 上下文Spring監聽器 --> <display-name>Spring3MVC</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 激活靜態資源的默認配置,解決Rest風格兼容 <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> --> <!-- ############################################################################## --> <!-- 歡迎頁面 --> <welcome-file-list> <welcome-file>startLogin.action</welcome-file> </welcome-file-list> <!-- ############################################################################## --> <!-- tomcat多項目啓動 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>web.lxyy_spring.root</param-value> </context-param> <!-- ############################################################################## --> <!-- google的驗證碼插件 --> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 全都要數字 --> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>0123456789</param-value> </init-param> <!-- 去掉干擾線 --> <init-param> <param-name>kaptcha.noise.impl</param-name> <param-value>com.google.code.kaptcha.impl.NoNoise </param-value> </init-param> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>65</param-value> </init-param> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>30</param-value> </init-param> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>25</param-value> </init-param> <init-param> <param-name>kaptcha.obscurificator.impl</param-name> <param-value>com.google.code.kaptcha.impl.ShadowGimpy</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping> <!-- ############################################################################## --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <!-- request監聽 --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener </listener-class> </listener> </web-app>
3. spring配置文件以下apache
注:須要解壓simple-spring-memcached-3.1.0.jar,找到simplesm-context.xml放到src目錄下api
<?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" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 引入jdbc配置文件 --> <context:property-placeholder location="classpath*:jdbc.properties"/> <!--建立jdbc數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClass}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> <!--初始化時獲取的鏈接數,取值應在minPoolSize與maxPoolSize之間。--> <property name="initialPoolSize" value="${initialPoolSize}"/> <!--鏈接池中保留的最小鏈接數。--> <property name="minPoolSize" value="${minPoolSize}"/> <!--鏈接池中保留的最大鏈接數。--> <property name="maxPoolSize" value="${maxPoolSize}"/> <!--最大空閒時間,60秒內未使用則鏈接被丟棄。若爲0則永不丟棄。--> <property name="maxIdleTime" value="${maxIdleTime}"/> <!--當鏈接池中的鏈接耗盡的時候c3p0一次同時獲取的鏈接數。--> <property name="acquireIncrement" value="${acquireIncrement}"/> <!--每60秒檢查全部鏈接池中的空閒鏈接。--> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 可經過註解控制事務 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 自動掃描bean,把做了註解的類轉換爲bean --> <context:component-scan base-package="com.dsideal" /> <!-- 加載組裝因此配置文件 context:component-scan註冊後能夠省略當前配置 <context:annotation-config /> --> <!-- 經過註解,把URL映射到Controller上,該標籤默認註冊RequestMappingHandlerMapping和RequestMappingHandlerAdapter --> <mvc:annotation-driven /> <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 --> <!--Spring3.1開始的註解 HandlerMapping <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!--Spring3.1開始的註解 HandlerAdapter <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- 啓用緩存註解 --> <cache:annotation-driven cache-manager="cacheManager"/> <bean id="cacheManager" class="org.springframework.cache.concurrent.ConcurrentMapCacheManager" /> <!-- 視圖解析器 InternalResourceViewResolver:支持jsp和jstl解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 使用JSP頁面進行輸出 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- 指定了表示層的前綴 --> <property name="prefix" value="/WEB-INF/bizroot/" /> <!-- 指定了表示層的後綴 --> <property name="suffix" value=".jsp" /> </bean> <!-- 處理文件上傳處理 maxUploadSize:最大上傳限制 uploadTempDir:上傳臨時路徑,文件上傳完成後,臨時目錄中的臨時文件會被自動清楚 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5242880" p:uploadTempDir="upload/temp"> </bean> <!-- 攔截器 <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.dsideal.common.SysInteceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> <!-- *********************** simple-spring-memcache ******************************* --> <!-- ssm 配置文件,主要用來加載組件核心的Advice,供程序調度使用;封裝在 simple-spring-memcached-3.1.0.jar 文件中--> <import resource="simplesm-context.xml" /> <!-- 讓代理機制起到做用,simple-spring-memcached主要是基於AOP的代理 --> <aop:aspectj-autoproxy /> <!-- com.google.code.ssm.CacheFactory是一個FactoryBean,會返回Cache(高速緩存)實體供Advice使用 --> <!-- FactoryBean解決的是如何建立沒法直接經過new運算符建立的Bean,並注入到其餘的bean中。也就是說FactoryBean是建立或者管理其餘被注入和管理Bean的工廠Bean --> <bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory"> <property name="cacheClientFactory"> <!-- xmemcached配置方法 --> <bean name="cacheClientFactory" class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" /> <!-- spymemcached配置方法 <bean name="cacheClientFactory" class="com.google.code.ssm.providers.spymemcached.MemcacheClientFactoryImpl" /> --> </property> <!-- 定義了緩存節點的IP地址和端口號 --> <property name="addressProvider"> <bean class="com.google.code.ssm.config.DefaultAddressProvider"> <property name="address" value="127.0.0.1:11211" /> </bean> </property> <!-- 定義了緩存節點的查找方法 --> <property name="configuration"> <bean class="com.google.code.ssm.providers.CacheConfiguration"> <property name="consistentHashing" value="true" /> </bean> </property> </bean> <!-- *********************** simple-spring-memcache ******************************* --> </beans>
4. Controller 類文件spring-mvc
package com.dsideal.sys.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.dsideal.sys.bean.SysLoginPersonBean; import com.dsideal.sys.service.ISysMemcachedTestService; @Controller public class SysLoginpersonController{ @Resource private ISysMemcachedTestService iSysMemcachedTestService; /** * <p>功能:登陸</p> * @author 周楓 * @date 2013-3-7 * @param * @return void */ @RequestMapping(value="/login",method=RequestMethod.POST) public void login(HttpServletRequest request,HttpServletResponse response,@RequestParam("yzm") String yzm,SysLoginPersonBean loginPerson) { try { //save person_id to memcached //loginPerson.setPerson_id("8BEFBA28-627D-4A37-BAF9-E33FC0F44169"); //iSysMemcachedTestService.saveLoginPerson(loginPerson); //get person_id from memcached // SysLoginPersonBean lpBean = new SysLoginPersonBean(); // lpBean = iSysMemcachedTestService.getByPersonId("8BEFBA28-627D-4A37-BAF9-E33FC0F44169"); // System.out.print(lpBean.getLogin_name()); //delete person_id from memcached iSysMemcachedTestService.deletePerson("8BEFBA28-627D-4A37-BAF9-E33FC0F44169"); } catch (Exception e) { e.printStackTrace(); } } }
5. service文件:緩存
package com.dsideal.sys.service; import com.dsideal.sys.bean.SysLoginPersonBean; import com.google.code.ssm.api.ParameterDataUpdateContent; import com.google.code.ssm.api.ParameterValueKeyProvider; public interface ISysMemcachedTestService { public void saveLoginPerson(SysLoginPersonBean lpBean); public SysLoginPersonBean getByPersonId(@ParameterValueKeyProvider String personId); public void updatePerson(@ParameterValueKeyProvider @ParameterDataUpdateContent SysLoginPersonBean lpBean); public void deletePerson(@ParameterValueKeyProvider String personId); }
6. serviceimpl文件:tomcat
解:組件所提供的切入點主要包括如下幾種:
ReadThroughSingleCache、ReadThroughMultiCache、ReadThroughAssignCache
當遇到查詢方法聲明這些切入點時,組件首先會從緩存中讀取數據,取到數據則跳過查詢方法,直接返回。
取不到數據在執行查詢方法,並將查詢結果放入緩存,以便下一次獲取。
InvalidateSingleCache、InvalidateMultiCache、InvalidateAssignCache
當遇到刪除方法聲明這些切入點時,組件會刪除緩存中的對應實體
UpdateSingleCache、UpdateMultiCache、UpdateAssignCache
當遇到更新方法聲明這些切入點是,組件會更新緩存中對應的實體,以便下次從緩存中讀取出的數據狀態是最新的mvc
package com.dsideal.sys.service.impl; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections.map.HashedMap; import org.springframework.stereotype.Service; import com.dsideal.sys.bean.SysLoginPersonBean; import com.dsideal.sys.service.ISysMemcachedTestService; import com.google.code.ssm.api.InvalidateSingleCache; import com.google.code.ssm.api.ParameterDataUpdateContent; import com.google.code.ssm.api.ParameterValueKeyProvider; import com.google.code.ssm.api.ReadThroughSingleCache; import com.google.code.ssm.api.UpdateSingleCache; @Service public class SysMemcachedTestServiceImpl implements ISysMemcachedTestService { private static final String NAMESPACE = "com.dsideal.sys.service.impl"; private Map<String,SysLoginPersonBean> person = new HashMap<String,SysLoginPersonBean>(); @Override public void saveLoginPerson(SysLoginPersonBean lpBean) { person.put(lpBean.getPerson_id(), lpBean); } /** * ReadThroughSingleCache、ReadThroughMultiCache、ReadThroughAssignCache 當遇到查詢方法聲明這些切入點時,組件首先會從緩存中讀取數據,取到數據則跳過查詢方法,直接返回。 取不到數據在執行查詢方法,並將查詢結果放入緩存,以便下一次獲取 */ @Override @ReadThroughSingleCache(namespace = NAMESPACE, expiration = 600) public SysLoginPersonBean getByPersonId(@ParameterValueKeyProvider String personId) { System.out.println(personId); return person.get(personId); } @Override @UpdateSingleCache(namespace = NAMESPACE, expiration = 600) public void updatePerson(@ParameterValueKeyProvider @ParameterDataUpdateContent SysLoginPersonBean lpBean) { person.put(lpBean.getPerson_id(), lpBean); } @Override @InvalidateSingleCache(namespace = NAMESPACE) public void deletePerson(@ParameterValueKeyProvider String personId) { person.remove(personId); } }
7. bean類
注:這裏bean必定要序列化,不然不能存入memcached
package com.dsideal.sys.bean; import java.io.Serializable; import com.google.code.ssm.api.CacheKeyMethod; @SuppressWarnings("serial") public class SysLoginPersonBean implements Serializable{ private String person_id; private String login_name; private String login_pwd; private int b_use; private int identity_id; private int bureau_id; private String real_name; @CacheKeyMethod public String getPerson_id() { return person_id; } public void setPerson_id(String person_id) { this.person_id = person_id; } public String getLogin_name() { return login_name; } public void setLogin_name(String login_name) { this.login_name = login_name; } public String getLogin_pwd() { return login_pwd; } public void setLogin_pwd(String login_pwd) { this.login_pwd = login_pwd; } public int getB_use() { return b_use; } public void setB_use(int b_use) { this.b_use = b_use; } public int getIdentity_id() { return identity_id; } public void setIdentity_id(int identity_id) { this.identity_id = identity_id; } public int getBureau_id() { return bureau_id; } public void setBureau_id(int bureau_id) { this.bureau_id = bureau_id; } public String getReal_name() { return real_name; } public void setReal_name(String real_name) { this.real_name = real_name; } public SysLoginPersonBean() { } public SysLoginPersonBean(String person_id,String login_name,String login_pwd,int b_use,int identity_id,int bureau_id,String real_name) { this.person_id = person_id; this.login_name = login_name; this.login_pwd = login_pwd; this.b_use = b_use; this.identity_id = identity_id; this.bureau_id = bureau_id; this.real_name = real_name; } }
英文官方配置:http://code.google.com/p/simple-spring-memcached/wiki/Getting_Started
本人配置時主要借鑑的文章:http://blog.csdn.net/javaman_chen/article/details/7682290
具體測試方法,我已經寫在controller裏面了,須要分開執行測試,也能夠參照本人以前寫的博客,原生態的memcached第二種測試方法進行測試,具體連接爲