SpringMVC-Mybatis-Memcached整合案例

一、.项目整体框架图如下:


依赖jar:


数据库设计:


二、项目搭建步骤:

步骤1.首先创建web工程,在WebContent目录下建立pages目录,在pages目录里创建login.jsp文件,其文件内容如下:

  1. <pre name="code" class="html"><%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"  
  3. %>  
  4. <%    
  5.     String path = request.getContextPath();   
  6.     String basePath =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  9. <html>  
  10. <head>  
  11. <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery/jquery-1.8.0.min.js"></script>  
  12. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  13. <title>Insert title here</title>  
  14. </head>  
  15. <body>  
  16.     <div><font color="red" size="10px">${user.gender}</font></div>  
  17.     <form action="${pageContext.request.contextPath }/loginController/login" method="post" name="loginForm" id="loginForm">  
  18.     <table style="text-align: right;">  
  19.           <tr>  
  20.               <td>用户名:</td>  
  21.               <td><input class="username" type="text" id="username" name="username"  value=''/></td>  
  22.           </tr>  
  23.           <tr>  
  24.               <td>密码:</td>  
  25.               <td><input class="password" type="password" id="password" name="password" value=""/></td>  
  26.           </tr>  
  27.         </table>  
  28.         <div><input type="button" value="提 交" onclick="login();" /></div>  
  29.     </form>   
  30. <span style="white-space:pre">    </span><script type="text/javascript">  
  31.       
  32.     function login(){  
  33.         var username = $("#username").val();  
  34.         var password = $("#password").val();  
  35.         $("#loginForm").submit();  
  36.     }  
  1.     document.onkeydown=function(event){   
  2.         e = event ? event :(window.event ? window.event : null);   
  3.         if(e.keyCode==13){   
  4.             login();  
  5.           }   
  6.        }   
  7. </script>  
  8. </body>  
  9. </html>  

步骤2.配置web.xml文件,文件内容:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>SpringMVC-Mybatis-Memcached</display-name>  
  4.    
  5.   <!-- 引入 spring -->  
  6.   <listener>  
  7.        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  8.   </listener>   
  9.   <context-param>  
  10.        <param-name>contextConfigLocation</param-name>  
  11.        <param-value>classpath*:/applicationContext*.xml</param-value>  
  12.   </context-param>  
  13.     
  14.   <!-- 引入 springMVC -->  
  15.   <servlet>  
  16.   <servlet-name>springMVC</servlet-name>  
  17.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  18.   <init-param>  
  19.        <param-name>contextConfigLocation</param-name>  
  20.        <param-value>classpath*:/spring-mvc-config.xml</param-value>  
  21.   </init-param>  
  22.   </servlet>    
  23.   <servlet-mapping>  
  24.        <servlet-name>springMVC</servlet-name>  
  25.        <url-pattern>/</url-pattern>  
  26.   </servlet-mapping>  
  27.     
  28.   <!-- 编码 UTF-8 -->  
  29.   <filter>  
  30.   <filter-name>SpringMVC-Memcached-Encoding</filter-name>  
  31.   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  32.   <init-param>  
  33.        <param-name>encoding</param-name>  
  34.        <param-value>UTF-8</param-value>  
  35.   </init-param>  
  36.   <init-param>  
  37.        <param-name>forceEncoding</param-name>  
  38.        <param-value>true</param-value>  
  39.   </init-param>  
  40.   </filter>  
  41.   <filter-mapping>  
  42.        <filter-name>SpringMVC-Memcached-Encoding</filter-name>  
  43.       <url-pattern>/*</url-pattern>  
  44.   </filter-mapping>  
  45.     
  46. </web-app>  

步骤3.创建spring-mvc-config.xml文件,配置内容:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:mvc="http://www.springframework.org/schema/mvc"    
  4.     xmlns:context="http://www.springframework.org/schema/context"    
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
  8.     http://www.springframework.org/schema/context     
  9.     http://www.springframework.org/schema/context/spring-context-3.1.xsd    
  10.     http://www.springframework.org/schema/mvc    
  11.     http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">    
  12.       
  13.     <!-- 使用@Controllers前配置 -->  
  14.     <mvc:annotation-driven />              
  15.       
  16.     <!-- 容器加载时 自动扫描所有注解 -->  
  17.     <context:component-scan base-package="com.test" />  
  18.       
  19.     <!-- 配置静态资源  -->      
  20.     <mvc:resources mapping="/js/**" location="/js/" />    
  21.     <mvc:resources mapping="/image/**" location="/image/" />   
  22.     <mvc:resources mapping="/css/**" location="/css/" />      
  23.       
  24.     <!-- 使用jsp作为视图 -->  
  25.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  26.         <property name="viewClass">  
  27.             <value>org.springframework.web.servlet.view.JstlView</value>  
  28.         </property>  
  29.         <!-- 目标路径返回到pages下 使用jsp作为视图 -->  
  30.         <property name="prefix" value="/pages/"></property>  
  31.         <property name="suffix" value=".jsp"></property>  
  32.     </bean>   
  33.       
  34.     <!-- 异常处理 -->  
  35.     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">      
  36.         <property name="exceptionMappings">      
  37.             <props>      
  38.                 <prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop>      
  39.             </props>      
  40.         </property>      
  41.     </bean>   
  42. </beans>  

步骤4.创建jdbc.properties文件,添加内容:

  1. jdbc.driverClassName=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc\:mysql\://localhost\:3306/demo?user\=root&password\=root  

步骤5.创建User对象:

  1. package com.test.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class User implements Serializable  
  6. {  
  7.   
  8.     private static final long serialVersionUID = -985141821084238350L;  
  9.   
  10.     private int id;  
  11.       
  12.     private String name;  
  13.       
  14.     private String gender;  
  15.       
  16.     public User()  
  17.     {  
  18.     }  
  19.   
  20.     public int getId()  
  21.     {  
  22.         return id;  
  23.     }  
  24.   
  25.     public void setId(int id)  
  26.     {  
  27.         this.id = id;  
  28.     }  
  29.   
  30.     public String getName()  
  31.     {  
  32.         return name;  
  33.     }  
  34.   
  35.     public void setName(String name)  
  36.     {  
  37.         this.name = name;  
  38.     }  
  39.   
  40.     public String getGender()  
  41.     {  
  42.         return gender;  
  43.     }  
  44.   
  45.     public void setGender(String gender)  
  46.     {  
  47.         this.gender = gender;  
  48.     }  
  49.       
  50. }  

步骤6.建立IUserDao接口:

  1. <pre name="code" class="java">package com.test.dao;  
  2.   
  3. import com.test.bean.User;  
  4.   
  5. public interface IUserDao  
  6. {  
  7.     public User getUser(String name);  
  8. }  

步骤7.创建IUserDao.xml文件,配置内容:

  1. <pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>   
  2. <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">   
  3. <!-- 务必配置正确namespace就是所映射的接口类-->   
  4. <mapper namespace="com.test.dao.IUserDao">    
  5. <!-- resultType="User"这个使用的是配置文件里面的别名(配置文件为mybatis-config.xml) -->   
  6. <select id="getUser" parameterType="string" resultType="User">           
  7.     select * from user where name=#{name}     
  8. </select>   
  9. </mapper>   

步骤9.创建MemcachedUtils工具类

  1. <pre name="code" class="java">package com.test.utils;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.io.StringWriter;  
  8. import java.lang.management.ManagementFactory;  
  9. import java.lang.management.RuntimeMXBean;  
  10. import java.text.SimpleDateFormat;  
  11. import java.util.Date;  
  12.   
  13. import org.apache.log4j.Logger;  
  14.   
  15. import com.danga.MemCached.MemCachedClient;  
  16.   
  17. public class MemcachedUtils  
  18. {  
  19.     private static final Logger logger = Logger.getLogger(MemcachedUtils.class);  
  20.     private static MemCachedClient cachedClient;  
  21.     static  
  22.     {  
  23.         if (cachedClient == null)  
  24.             cachedClient = new MemCachedClient("memcachedPool");  
  25.     }  
  26.   
  27.     private MemcachedUtils()  
  28.     {  
  29.     }  
  30.   
  31.     /** 
  32.      * 向缓存添加新的键值对。如果键已经存在,则之前的值将被替换。 
  33.      *  
  34.      * @param key 
  35.      *            键 
  36.      * @param value 
  37.      *            值 
  38.      * @return 
  39.      */  
  40.     public static boolean set(String key, Object value)  
  41.     {  
  42.         return setExp(key, value, null);  
  43.     }  
  44.   
  45.     /** 
  46.      * 向缓存添加新的键值对。如果键已经存在,则之前的值将被替换。 
  47.      *  
  48.      * @param key 
  49.      *            键 
  50.      * @param value 
  51.      *            值 
  52.      * @param expire 
  53.      *            过期时间 New Date(1000*10):十秒后过期 
  54.      * @return 
  55.      */  
  56.     public static boolean set(String key, Object value, Date expire)  
  57.     {  
  58.         return setExp(key, value, expire);  
  59.     }  
  60.   
  61.     /** 
  62.      * 向缓存添加新的键值对。如果键已经存在,则之前的值将被替换。 
  63.      *  
  64.      * @param key 
  65.      *            键 
  66.      * @param value 
  67.      *            值 
  68.      * @param expire 
  69.      *            过期时间 New Date(1000*10):十秒后过期 
  70.      * @return 
  71.      */  
  72.     private static boolean setExp(String key, Object value, Date expire)  
  73.     {  
  74.         boolean flag = false;  
  75.         try  
  76.         {  
  77.             flag = cachedClient.set(key, value, expire);  
  78.         }  
  79.         catch (Exception e)  
  80.         {  
  81.             // 记录Memcached日志  
  82.             MemcachedLog.writeLog("Memcached set方法报错,key值:" + key + "\r\n" + exceptionWrite(e));  
  83.         }  
  84.         return flag;  
  85.     }  
  86.   
  87.     /** 
  88.      * 仅当缓存中不存在键时,add 命令才会向缓存中添加一个键值对。 
  89.      *  
  90.      * @param key 
  91.      *            键 
  92.      * @param value 
  93.      *            值 
  94.      * @return 
  95.      */  
  96.     public static boolean add(String key, Object value)  
  97.     {  
  98.         return addExp(key, value, null);  
  99.     }  
  100.   
  101.     /** 
  102.      * 仅当缓存中不存在键时,add 命令才会向缓存中添加一个键值对。 
  103.      *  
  104.      * @param key 
  105.      *            键 
  106.      * @param value 
  107.      *            值 
  108.      * @param expire 
  109.      *            过期时间 New Date(1000*10):十秒后过期 
  110.      * @return 
  111.      */  
  112.     public static boolean add(String key, Object value, Date expire)  
  113.     {  
  114.         return addExp(key, value, expire);  
  115.     }  
  116.   
  117.     /** 
  118.      * 仅当缓存中不存在键时,add 命令才会向缓存中添加一个键值对。 
  119.      *  
  120.      * @param key 
  121.      *            键 
  122.      * @param value 
  123.      *            值 
  124.      * @param expire 
  125.      *            过期时间 New Date(1000*10):十秒后过期 
  126.      * @return 
  127.      */  
  128.     private static boolean addExp(String key, Object value, Date expire)  
  129.     {  
  130.         boolean flag = false;  
  131.         try  
  132.         {  
  133.             flag = cachedClient.add(key, value, expire);  
  134.         }  
  135.         catch (Exception e)  
  136.         {  
  137.             // 记录Memcached日志  
  138.             MemcachedLog.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(e));  
  139.         }  
  140.         return flag;  
  141.     }  
  142.   
  143.     /** 
  144.      * 仅当键已经存在时,replace 命令才会替换缓存中的键。 
  145.      *  
  146.      * @param key 
  147.      *            键 
  148.      * @param value 
  149.      *            值 
  150.      * @return 
  151.      */  
  152.     public static boolean replace(String key, Object value)  
  153.     {  
  154.         return replaceExp(key, value, null);  
  155.     }  
  156.   
  157.     /** 
  158.      * 仅当键已经存在时,replace 命令才会替换缓存中的键。 
  159.      *  
  160.      * @param key 
  161.      *            键 
  162.      * @param value 
  163.      *            值 
  164.      * @param expire 
  165.      *            过期时间 New Date(1000*10):十秒后过期 
  166.      * @return 
  167.      */  
  168.     public static boolean replace(String key, Object value, Date expire)  
  169.     {  
  170.         return replaceExp(key, value, expire);  
  171.     }  
  172.   
  173.     /** 
  174.      * 仅当键已经存在时,replace 命令才会替换缓存中的键。 
  175.      *  
  176.      * @param key 
  177.      *            键 
  178.      * @param value 
  179.      *            值 
  180.      * @param expire 
  181.      *            过期时间 New Date(1000*10):十秒后过期 
  182.      * @return 
  183.      */  
  184.     private static boolean replaceExp(String key, Object value, Date expire)  
  185.     {  
  186.         boolean flag = false;  
  187.         try  
  188.         {  
  189.             flag = cachedClient.replace(key, value, expire);  
  190.         }  
  191.         catch (Exception e)  
  192.         {  
  193.             MemcachedLog.writeLog("Memcached replace方法报错,key值:" + key + "\r\n" + exceptionWrite(e));  
  194.         }  
  195.         return flag;  
  196.     }  
  197.   
  198.     /** 
  199.      * get 命令用于检索与之前添加的键值对相关的值。 
  200.      *  
  201.      * @param key 
  202.      *            键 
  203.      * @return 
  204.      */  
  205.     public static Object get(String key)  
  206.     {  
  207.         Object obj = null;  
  208.         try  
  209.         {  
  210.             obj = cachedClient.get(key);  
  211.         }  
  212.         catch (Exception e)  
  213.         {  
  214.             MemcachedLog.writeLog("Memcached get方法报错,key值:" + key + "\r\n" + exceptionWrite(e));  
  215.         }  
  216.         return obj;  
  217.     }  
  218.   
  219.     /** 
  220.      * 删除 memcached 中的任何现有值。 
  221.      *  
  222.      * @param key 
  223.      *            键 
  224.      * @return 
  225.      */  
  226.     public static boolean delete(String key)  
  227.     {  
  228.         return deleteExp(key, null);  
  229.     }  
  230.   
  231.     /** 
  232.      * 删除 memcached 中的任何现有值。 
  233.      *  
  234.      * @param key 
  235.      *            键 
  236.      * @param expire 
  237.      *            过期时间 New Date(1000*10):十秒后过期 
  238.      * @return 
  239.      */  
  240.     public static boolean delete(String key, Date expire)  
  241.     {  
  242.         return deleteExp(key, expire);  
  243.     }  
  244.   
  245.     /** 
  246.      * 删除 memcached 中的任何现有值。 
  247.      *  
  248.      * @param key 
  249.      *            键 
  250.      * @param expire 
  251.      *            过期时间 New Date(1000*10):十秒后过期 
  252.      * @return 
  253.      */  
  254.     private static boolean deleteExp(String key, Date expire)  
  255.     {  
  256.         boolean flag = false;  
  257.         try  
  258.         {  
  259.             flag = cachedClient.delete(key, expire);  
  260.         }  
  261.         catch (Exception e)  
  262.         {  
  263.             MemcachedLog.writeLog("Memcached delete方法报错,key值:" + key + "\r\n" + exceptionWrite(e));  
  264.         }  
  265.         return flag;  
  266.     }  
  267.   
  268.     /** 
  269.      * 清理缓存中的所有键/值对 
  270.      *  
  271.      * @return 
  272.      */  
  273.     public static boolean flashAll()  
  274.     {  
  275.         boolean flag = false;  
  276.         try  
  277.         {  
  278.             flag = cachedClient.flushAll();  
  279.         }  
  280.         catch (Exception e)  
  281.         {  
  282.             MemcachedLog.writeLog("Memcached flashAll方法报错\r\n" + exceptionWrite(e));  
  283.         }  
  284.         return flag;  
  285.     }  
  286.   
  287.     /** 
  288.      * 返回异常栈信息,String类型 
  289.      *  
  290.      * @param e 
  291.      * @return 
  292.      */  
  293.     private static String exceptionWrite(Exception e)  
  294.     {  
  295.         StringWriter sw = new StringWriter();  
  296.         PrintWriter pw = new PrintWriter(sw);  
  297.         e.printStackTrace(pw);  
  298.         pw.flush();  
  299.         return sw.toString();  
  300.     }  
  301.   
  302.     /** 
  303.      *  
  304.      * @ClassName: MemcachedLog 
  305.      * @Description: Memcached日志记录 
  306.      *  
  307.      */  
  308.     private static class MemcachedLog  
  309.     {  
  310.         private final static String MEMCACHED_LOG = "D:\\memcached.log";  
  311.         private final static String LINUX_MEMCACHED_LOG = "/usr/local/logs/memcached.log";  
  312.         private static FileWriter fileWriter;  
  313.         private static BufferedWriter logWrite;  
  314.         // 获取PID,可以找到对应的JVM进程  
  315.         private final static RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();  
  316.         private final static String PID = runtime.getName();  
  317.   
  318.         /** 
  319.          * 初始化写入流 
  320.          */  
  321.         static  
  322.         {  
  323.             try  
  324.             {  
  325.                 String osName = System.getProperty("os.name");  
  326.                 if (osName.indexOf("Windows") == -1)  
  327.                 {  
  328.                     fileWriter = new FileWriter(MEMCACHED_LOG, true);  
  329.                 }  
  330.                 else  
  331.                 {  
  332.                     fileWriter = new FileWriter(LINUX_MEMCACHED_LOG, true);  
  333.                 }  
  334.                 logWrite = new BufferedWriter(fileWriter);  
  335.             }  
  336.             catch (IOException e)  
  337.             {  
  338.                 logger.error("memcached 日志初始化失败", e);  
  339.                 closeLogStream();  
  340.             }  
  341.         }  
  342.   
  343.         /** 
  344.          * 写入日志信息 
  345.          *  
  346.          * @param content 
  347.          *            日志内容 
  348.          */  
  349.         public static void writeLog(String content)  
  350.         {  
  351.             try  
  352.             {  
  353.                 logWrite.write("[" + PID + "] " + "- ["  
  354.                         + new SimpleDateFormat("yyyy年-MM月-dd日 hh时:mm分:ss秒").format(new Date().getTime()) + "]\r\n"  
  355.                         + content);  
  356.                 logWrite.newLine();  
  357.                 logWrite.flush();  
  358.             }  
  359.             catch (IOException e)  
  360.             {  
  361.                 logger.error("memcached 写入日志信息失败", e);  
  362.             }  
  363.         }  
  364.   
  365.         /** 
  366.          * 关闭流 
  367.          */  
  368.         private static void closeLogStream()  
  369.         {  
  370.             try  
  371.             {  
  372.                 fileWriter.close();  
  373.                 logWrite.close();  
  374.             }  
  375.             catch (IOException e)  
  376.             {  
  377.                 logger.error("memcached 日志对象关闭失败", e);  
  378.             }  
  379.         }  
  380.     }  
  381. }  

步骤10.创建IUserServer接口:

  1. <pre name="code" class="java">package com.test.server;  
  2.   
  3. import com.test.bean.User;  
  4.   
  5. public interface IUserServer  
  6. {  
  7.     public User testMethod(String userName);  
  8. }  

步骤11.创建UserServerImpl.Java类实现IUserServer接口:

  1. <pre name="code" class="java">package com.test.server;  
  2.   
  3. import net.spy.memcached.MemcachedClient;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import com.test.bean.User;  
  8. import com.test.dao.IUserDao;  
  9.   
  10. public class UserServerImpl implements IUserServer  
  11. {  
  12.   
  13.     private IUserDao userDao;  
  14.     private MemcachedClient memcachedClient;  
  15.       
  16.     public User testMethod(String userName)  
  17.     {  
  18.         User user;  
  19.         // 判断缓存中数据是否存在,如果不存在则添加,存在则读取  
  20.         if (this.memcachedClient.get("user") != null)  
  21.         {  
  22.             user = (User) this.memcachedClient.get("user");  
  23.             System.out.println("本次操作是在缓存中查询数据...");  
  24.         }  
  25.         else  
  26.         {  
  27.             user = userDao.getUser(userName);  
  28.             this.memcachedClient.add("user"100, user);  
  29.             System.out.println("本次操作是在数据库中查询数据...");  
  30.         }  
  31.         return user;  
  32.     }  
  33.       
  34.     public IUserDao getUserDao()  
  35.     {  
  36.         return userDao;  
  37.     }  
  38.     // 依赖注入,根据属性名自动注入  
  39.     @Autowired  
  40.     public void setUserDao(IUserDao userDao)  
  41.     {  
  42.         this.userDao = userDao;  
  43.     }  
  44.       
  45.     public MemcachedClient getMemcachedClient()  
  46.     {  
  47.         return memcachedClient;  
  48.     }  
  49.     // 依赖注入(分布式缓存,在spring中自动生成)  
  50.     @Autowired  
  51.     public void setMemcachedClient(MemcachedClient memcachedClient)  
  52.     {  
  53.         this.memcachedClient = memcachedClient;  
  54.     }  
  55.       
  56. }  

步骤12.创建LoginController:

  1. <pre name="code" class="java">package com.test.web;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.servlet.ModelAndView;  
  10.   
  11. import com.test.bean.User;  
  12. import com.test.server.IUserServer;  
  13.   
  14. @Controller  
  15. @RequestMapping("/loginController")  
  16. public class LoginController  
  17. {  
  18.   
  19.     IUserServer server;  
  20.   
  21.     // 根据访问连接调用控制器,此控制器的调用连接为localhost:8080/SpringMVC-Mybatis-Memcached/loginController/login  
  22.     @RequestMapping("login")  
  23.     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception  
  24.     {  
  25.         // 创建ModelAndView对象,login为返回的jsp页面的名称,全路径是根据在springMVC配置文件中配置的前缀与后缀拼接而成  
  26.         ModelAndView mode = new ModelAndView("login");  
  27.         User user = server.testMethod("aa");  
  28.         // 将对象加入mode返回到前台页面  
  29.         mode.addObject("user", user);  
  30.         return mode;  
  31.     }  
  32.   
  33.     public IUserServer getServer()  
  34.     {  
  35.         return server;  
  36.     } // 依赖注入,根据属性名自动注入  
  37.     @Autowired  
  38.     public void setServer(IUserServer server)  
  39.     {  
  40.         this.server = server;  
  41.     }  
  42. }  

步骤13.创建spring-memcached.xml文件,添加内容:

  1. <pre name="code" class="html"><?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:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
  8.     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
  9.     http://www.springframework.org/schema/context     
  10.     http://www.springframework.org/schema/context/spring-context-3.1.xsd    
  11.     http://www.springframework.org/schema/aop     
  12.     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
  13.     http://www.springframework.org/schema/tx     
  14.     http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">  
  15.       
  16.     <!--memcached注入 -->  
  17.     <bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">  
  18.         <property name="servers" value="127.0.0.1:11211" />  
  19.         <property name="protocol" value="BINARY" />  
  20.         <property name="transcoder">  
  21.             <bean class="net.spy.memcached.transcoders.SerializingTranscoder">  
  22.                 <property name="compressionThreshold" value="1024" />  
  23.             </bean>  
  24.         </property>  
  25.         <property name="opTimeout" value="50" />  
  26.         <property name="timeoutExceptionThreshold" value="1998" />  
  27.         <property name="hashAlg">  
  28.             <value type="net.spy.memcached.DefaultHashAlgorithm">KETAMA_HASH</value>  
  29.         </property>  
  30.         <property name="locatorType" value="CONSISTENT" />  
  31.         <property name="failureMode" value="Redistribute" />  
  32.         <property name="useNagleAlgorithm" value="false" />  
  33.     </bean>  
  34. </beans>  

步骤14.创建applicationContext.xml文件,配置其内容:

  1. <pre name="code" class="html"><?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" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans                
  6.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd               
  7.        http://www.springframework.org/schema/context                
  8.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  9.     <!-- 获取JDBC连接属性 -->  
  10.     <context:property-placeholder location="classpath:jdbc.properties" />  
  11.     <!-- 配置数据源 -->  
  12.     <bean id="dataSource"  
  13.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  14.         <property name="driverClassName" value="${jdbc.driverClassName}"></property>  
  15.         <property name="url" value="${jdbc.url}">  
  16.         </property>  
  17.     </bean>  
  18.     <!-- sqlSessionFactory -->  <!-- MyBatis在spring中Bean的配置,都是固定的 -->  
  19.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  20.         <property name="configLocation" value="classpath:mybatis-config.xml" />  
  21.         <property name="dataSource" ref="dataSource" />  
  22.     </bean>  
  23.     <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
  24.         <constructor-arg index="0" ref="sqlSessionFactory" />  
  25.     </bean>  
  26.     <!-- 引入memcached配置文件 -->  
  27.     <import resource="spring-memcached.xml"/>  
  28.     <!-- 配置映射器 -->  
  29.     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">  
  30.         <property name="mapperInterface" value="com.test.dao.IUserDao" />  
  31.         <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
  32.     </bean>  
  33.     <!-- 为业务逻辑层注入数据的对象 -->  
  34.     <bean id="userServer" class="com.test.server.UserServerImpl">  
  35.         <property name="userDao" ref="userMapper"></property>  
  36.         <property name="memcachedClient" ref="memcachedClient"></property>  
  37.     </bean>  
  38.     <bean id="login" class="com.test.web.LoginController">  
  39.         <property name="server" ref="userServer"></property>  
  40.     </bean>  
  41. </beans>  

猜你喜欢

转载自blog.csdn.net/aglne/article/details/75096442