身在一個傳統的IT公司,接觸的新技術比較少,打算年後跳槽,因此抽空學了一下redis。html
簡單的redis測試,我們這邊就不講了,如今主要講講ssm集成redis的過程,由於如今項目用的就是ssm的框架。java
好了,廢話不說,上代碼:mysql
Pom.xmlgit
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssm</groupId> <artifactId>ssmDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssmDemo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日誌文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示開發的時候引入,發佈的時候不會加載此包 --> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.9.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 導入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 導入Mysql數據庫連接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日誌文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- Redis客戶端jedis依賴 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.0</version> </dependency> <!-- spring-data-redis依賴 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.5.0.RELEASE</version> </dependency> <!-- 格式化對象,方便輸出日誌 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上傳組件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>ssmDemo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
配置文件:github
spring-mvc.xmlweb
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 --> <context:component-scan base-package="com.ssm" /> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 --> </list> </property> </bean> <!-- 定義跳轉的文件的先後綴 ,視圖模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上傳,若是沒有使用文件上傳能夠不用配置,固然若是不配,那麼配置文件中也沒必要引入上傳組件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默認編碼 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 內存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
mybatis-config.xmlredis
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 這個配置使全局的映射器啓用或禁用緩存 --> <setting name="cacheEnabled" value="true" /> <!-- 對於未知的SQL查詢,容許返回不一樣的結果集以達到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 配置默認的執行器。SIMPLE 執行器沒有什麼特別之處。REUSE 執行器重用預處理語句。BATCH 執行器重用語句和批量更新 --> <setting name="defaultExecutorType" value="REUSE" /> <!-- 全局啓用或禁用延遲加載。當禁用時,全部關聯對象都會即時加載。 --> <setting name="lazyLoadingEnabled" value="false" /> <setting name="aggressiveLazyLoading" value="true" /> <!-- 設置超時時間,它決定驅動等待一個數據庫響應的時間。 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <mappers> <mapper resource="com/ssm/mapping/UserMapper.xml" /> </mappers> </configuration>
spring-mybatis.xmlspring
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化鏈接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 鏈接池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 鏈接池最大空閒 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取鏈接最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
applicationContext.xmlsql
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!--其實component-scan 就有了annotation-config的功能即把須要的類註冊到了spring容器中 --> <context:component-scan base-package="com。ssm.service" /> <!--配置事務註解 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- redis配置 --> <!-- redis鏈接池 --> <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="300"></property> <property name="maxIdle" value="200"></property> <property name="MaxWaitMillis" value="10000"></property> <property name="testOnBorrow" value="true"></property> <property name="testOnReturn" value="true"></property> </bean> <!-- redis鏈接工廠 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="127.0.0.1"></property> <property name="port" value="6379"></property> <property name="poolConfig" ref="jedisConfig"></property> </bean> <!-- redis操做模板,這裏採用儘可能面向對象的模板 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> </bean> </beans>
jdbc.properties數據庫
driver=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost\:3306/production_ssm username=root password=123456 #\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570 initialSize=0 #\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570 maxActive=20 #\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2 maxIdle=20 #\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2 minIdle=1 #\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4 maxWait=60000
log4j.properties
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n #log4j.appender.R=org.apache.log4j.DailyRollingFileAppender #log4j.appender.R.File=../logs/service.log #log4j.appender.R.layout=org.apache.log4j.PatternLayout #log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n log4j.logger.com.ibatis = debug log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug log4j.logger.java.sql.Connection = debug log4j.logger.java.sql.Statement = debug log4j.logger.java.sql.PreparedStatement = debug log4j.logger.java.sql.ResultSet =debug
web.xml
<?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" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml,classpath:applicationContext.xml</param-value> </context-param> <!-- 編碼過濾器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- Spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring內存溢出監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此處能夠能夠配置成*.do,對應struts的後綴習慣 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
以上是一些相關的配置項,接下來是真正的java代碼:
UserController.java
package com.ssm.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ssm.pojo.User; import com.ssm.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/showUser") public String toIndex(HttpServletRequest request, Model model) { int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.selectByPrimaryKey(userId); model.addAttribute("user", user); return "showUser"; } }
UserService.java
package com.ssm.service; import com.ssm.pojo.User; public interface UserService { User selectByPrimaryKey(Integer id); }
UserServiceImpl.java
package com.ssm.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssm.dao.UserMapper; import com.ssm.pojo.User; import com.ssm.service.UserService; @Service("userServiceImpl") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; public User selectByPrimaryKey(Integer id) { return userMapper.selectByPrimaryKey(id); } }
UserMapper.java
package com.ssm.dao; import com.ssm.pojo.User; public interface UserMapper { User selectByPrimaryKey(Integer id); }
UserExample.java是經過mybaitis的插件自動生成的,就不寫了,後面提供源碼。
User.java
package com.ssm.pojo; import java.io.Serializable; /** * user 類 * * @author fhliuzhihu * */ public class User implements Serializable { /** * 使用jedis 須要序列化接口 */ private static final long serialVersionUID = 1L; private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", username=" + userName + ", password=" + password + ",age=" + age + "]"; } }
RedisCache.java
package com.ssm.redis; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache; import org.springframework.beans.factory.annotation.Autowired; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisCache implements Cache { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); /** * Jedis客戶端 */ @Autowired private Jedis redisClient = createClient(); private String id; public RedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("必須傳入ID"); } System.out.println("MybatisRedisCache:id=" + id); this.id = id; } @Override public void clear() { redisClient.flushDB(); } @Override public String getId() { return this.id; } @Override public Object getObject(Object key) { byte[] ob = redisClient.get(SerializeUtil.serialize(key.toString())); if (ob == null) { return null; } Object value = SerializeUtil.unSerialize(ob); return value; } @Override public ReadWriteLock getReadWriteLock() { return readWriteLock; } @Override public int getSize() { return Integer.valueOf(redisClient.dbSize().toString()); } @Override public void putObject(Object key, Object value) { redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value)); } @Override public Object removeObject(Object key) { return redisClient.expire(SerializeUtil.serialize(key.toString()), 0); } protected static Jedis createClient() { try { @SuppressWarnings("resource") JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1", 6379); return pool.getResource(); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("初始化鏈接池錯誤"); } }
SerializeUtil.java
package com.ssm.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeUtil { /** * * 序列化 */ public static byte[] serialize(Object obj) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { // 序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(obj); byte[] byteArray = baos.toByteArray(); return byteArray; } catch (IOException e) { e.printStackTrace(); } return null; } /** * * 反序列化 * * @param bytes * @return */ public static Object unSerialize(byte[] bytes) { ByteArrayInputStream bais = null; try { // 反序列化爲對象 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } }
最後,UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ssm.dao.UserMapper"> <cache type="com.ssm.redis.RedisCache" /> <resultMap id="BaseResultMap" type="com.ssm.pojo.User"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="user_name" jdbcType="VARCHAR" property="userName" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> id, user_name, password, age </sql> <select id="selectByExample" parameterType="com.ssm.dao.UserExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from user_t <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user_t where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user_t where id = #{id,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.ssm.dao.UserExample"> delete from user_t <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.ssm.pojo.User"> insert into user_t (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.ssm.pojo.User"> insert into user_t <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="userName != null"> user_name, </if> <if test="password != null"> password, </if> <if test="age != null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <select id="countByExample" parameterType="com.ssm.dao.UserExample" resultType="java.lang.Integer"> select count(*) from user_t <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update user_t <set> <if test="record.id != null"> id = #{record.id,jdbcType=INTEGER}, </if> <if test="record.userName != null"> user_name = #{record.userName,jdbcType=VARCHAR}, </if> <if test="record.password != null"> password = #{record.password,jdbcType=VARCHAR}, </if> <if test="record.age != null"> age = #{record.age,jdbcType=INTEGER}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update user_t set id = #{record.id,jdbcType=INTEGER}, user_name = #{record.userName,jdbcType=VARCHAR}, password = #{record.password,jdbcType=VARCHAR}, age = #{record.age,jdbcType=INTEGER} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.ssm.pojo.User"> update user_t <set> <if test="userName != null"> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.ssm.pojo.User"> update user_t set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
其中,UserMapper.xml中,最重要的就是
<cache type="com.ssm.redis.RedisCache" />
這個是須要緩存哪一個實體類,那麼就在哪一個的mapper.xml中添加上這一句!
測試:
啓動本地的redis,而後啓動項目,瀏覽器中輸入:http://localhost:8080/ssmDemo/user/showUser?id=1
後臺日誌:
第一次,直接查詢數據庫數據。
經過RedisDesktopManager查詢本地redis,發現數據已經存在了redis中:
再次刷新頁面,查看後臺日誌:
ok,ssm集成redis的步驟就是這些了,不過怎麼說呢,仍是有點兒問題,就是RedisCache得到Jedis的過程,我以爲應該是須要直接經過@Autowired獲取,可是我這個就是經過createClient();這個方法獲取的,因此有問題,回頭看看怎麼更改吧!
好吧,代碼寫的很渣,可是仍是放上去,供你們參考一下,一塊兒學習吧!
加油!