SSM 整合Redis缓存数据库 + RedisTemplate对象的使用,Spring Cache注解的使用 (第三章)
SSM项目架构搭建
该图是一个搭建好了的SSM项目结构,用maven管理项目依赖。
一,添加项目依赖(我直接贴pom.xml文件了)
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>indi.lwc</groupId> 8 <artifactId>Spring_Redis_Demo</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>Spring_Redis_Demo Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <spring.version>4.3.7.RELEASE</spring.version> 18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 19 <maven.compiler.source>1.7</maven.compiler.source> 20 <maven.compiler.target>1.7</maven.compiler.target> 21 </properties> 22 23 <dependencies> 24 25 <!--junit单元测试--> 26 <dependency> 27 <groupId>junit</groupId> 28 <artifactId>junit</artifactId> 29 <version>4.12</version> 30 <scope>test</scope> 31 </dependency> 32 33 <!-- 2.数据库 --> 34 <dependency> 35 <groupId>mysql</groupId> 36 <artifactId>mysql-connector-java</artifactId> 37 <version>5.1.37</version> 38 <scope>runtime</scope> 39 </dependency> 40 41 <!-- DAO: MyBatis --> 42 <dependency> 43 <groupId>org.mybatis</groupId> 44 <artifactId>mybatis</artifactId> 45 <version>3.4.2</version> 46 </dependency> 47 <dependency> 48 <groupId>org.mybatis</groupId> 49 <artifactId>mybatis-spring</artifactId> 50 <version>1.3.1</version> 51 </dependency> 52 53 <!-- 3.Servlet web --> 54 <dependency> 55 <groupId>taglibs</groupId> 56 <artifactId>standard</artifactId> 57 <version>1.1.2</version> 58 </dependency> 59 <dependency> 60 <groupId>jstl</groupId> 61 <artifactId>jstl</artifactId> 62 <version>1.2</version> 63 </dependency> 64 <dependency> 65 <groupId>com.fasterxml.jackson.core</groupId> 66 <artifactId>jackson-databind</artifactId> 67 <version>2.8.7</version> 68 </dependency> 69 <dependency> 70 <groupId>javax.servlet</groupId> 71 <artifactId>javax.servlet-api</artifactId> 72 <version>3.1.0</version> 73 </dependency> 74 75 <!-- 4.Spring --> 76 <!-- 1)Spring核心 --> 77 <dependency> 78 <groupId>org.springframework</groupId> 79 <artifactId>spring-core</artifactId> 80 <version>${spring.version}</version> 81 </dependency> 82 <dependency> 83 <groupId>org.springframework</groupId> 84 <artifactId>spring-beans</artifactId> 85 <version>${spring.version}</version> 86 </dependency> 87 <dependency> 88 <groupId>org.springframework</groupId> 89 <artifactId>spring-context</artifactId> 90 <version>${spring.version}</version> 91 </dependency> 92 <!-- 2)Spring DAO层 --> 93 <dependency> 94 <groupId>org.springframework</groupId> 95 <artifactId>spring-jdbc</artifactId> 96 <version>${spring.version}</version> 97 </dependency> 98 <dependency> 99 <groupId>org.springframework</groupId> 100 <artifactId>spring-tx</artifactId> 101 <version>${spring.version}</version> 102 </dependency> 103 <!-- 3)Spring web --> 104 <dependency> 105 <groupId>org.springframework</groupId> 106 <artifactId>spring-web</artifactId> 107 <version>${spring.version}</version> 108 </dependency> 109 <dependency> 110 <groupId>org.springframework</groupId> 111 <artifactId>spring-webmvc</artifactId> 112 <version>${spring.version}</version> 113 </dependency> 114 <!-- 4)Spring test --> 115 <dependency> 116 <groupId>org.springframework</groupId> 117 <artifactId>spring-test</artifactId> 118 <version>${spring.version}</version> 119 </dependency> 120 121 <!-- Map工具类 --> 122 <dependency> 123 <groupId>commons-collections</groupId> 124 <artifactId>commons-collections</artifactId> 125 <version>3.2</version> 126 </dependency> 127 <dependency> 128 <groupId>net.coobird</groupId> 129 <artifactId>thumbnailator</artifactId> 130 <version>0.4.8</version> 131 </dependency> 132 <dependency> 133 <groupId>com.github.penggle</groupId> 134 <artifactId>kaptcha</artifactId> 135 <version>2.3.2</version> 136 </dependency> 137 <dependency> 138 <groupId>commons-fileupload</groupId> 139 <artifactId>commons-fileupload</artifactId> 140 <version>1.3.2</version> 141 </dependency> 142 <dependency> 143 <groupId>net.sf.json-lib</groupId> 144 <artifactId>json-lib</artifactId> 145 <version>2.4</version> 146 <classifier>jdk15</classifier> 147 <exclusions> 148 <exclusion> 149 <artifactId>commons-collections</artifactId> 150 <groupId>commons-collections</groupId> 151 </exclusion> 152 <exclusion> 153 <artifactId>commons-lang</artifactId> 154 <groupId>commons-lang</groupId> 155 </exclusion> 156 <exclusion> 157 <artifactId>commons-logging</artifactId> 158 <groupId>commons-logging</groupId> 159 </exclusion> 160 </exclusions> 161 </dependency> 162 <dependency> 163 <groupId>com.thoughtworks.xstream</groupId> 164 <artifactId>xstream</artifactId> 165 <version>1.4.9</version> 166 </dependency> 167 <dependency> 168 <groupId>org.apache.taglibs</groupId> 169 <artifactId>taglibs-standard-spec</artifactId> 170 <version>1.2.1</version> 171 </dependency> 172 <dependency> 173 <groupId>org.apache.taglibs</groupId> 174 <artifactId>taglibs-standard-impl</artifactId> 175 <version>1.2.1</version> 176 </dependency> 177 <dependency> 178 <groupId>org.dom4j</groupId> 179 <artifactId>dom4j</artifactId> 180 <version>2.0.0</version> 181 </dependency> 182 183 <!--c3p0连接池--> 184 <dependency> 185 <groupId>c3p0</groupId> 186 <artifactId>c3p0</artifactId> 187 <version>0.9.1.2</version> 188 </dependency> 189 190 <!--redis相关--> 191 <dependency> 192 <groupId>redis.clients</groupId> 193 <artifactId>jedis</artifactId> 194 <version>2.9.0</version> 195 </dependency> 196 <dependency> 197 <groupId>org.springframework.data</groupId> 198 <artifactId>spring-data-redis</artifactId> 199 <version>1.6.2.RELEASE</version> 200 </dependency> 201 202 <dependency> 203 <groupId>org.mybatis</groupId> 204 <artifactId>mybatis-ehcache</artifactId> 205 <version>1.0.0</version> 206 </dependency> 207 208 209 </dependencies> 210 211 <build> 212 <finalName>Spring_Redis_Demo</finalName> 213 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 214 <plugins> 215 <!--clean 构建之后清理目标文件。删除目标目录--> 216 <plugin> 217 <artifactId>maven-clean-plugin</artifactId> 218 <version>3.1.0</version> 219 </plugin> 220 <!--处理项目的资源文件拷贝到输入目录 可分别处理 main resources 和 test resources--> 221 <plugin> 222 <artifactId>maven-resources-plugin</artifactId> 223 <version>3.0.2</version> 224 </plugin> 225 <!--compiler 编译java源文件--> 226 <plugin> 227 <artifactId>maven-compiler-plugin</artifactId> 228 <version>3.8.0</version> 229 <configuration> 230 <source>1.7</source><!--源代码使用的jdk版本--> 231 <target>1.7</target><!--需要生成的目标class文件的编译版本--> 232 <encoding>UTF-8</encoding><!-- 字符集编码 --> 233 </configuration> 234 </plugin> 235 <!--运行Junit单元测试,创建测试报告--> 236 <plugin> 237 <artifactId>maven-surefire-plugin</artifactId> 238 <version>2.22.1</version> 239 </plugin> 240 <!--从当前工程中构建WAR文件--> 241 <plugin> 242 <artifactId>maven-war-plugin</artifactId> 243 <version>3.2.2</version> 244 </plugin> 245 <!--install 安装打包到本地仓库,以供其它项目使用--> 246 <plugin> 247 <artifactId>maven-install-plugin</artifactId> 248 <version>2.5.2</version> 249 </plugin> 250 <!--部署 拷贝最终的工程到远程仓库,供其它开发人员使用--> 251 <plugin> 252 <artifactId>maven-deploy-plugin</artifactId> 253 <version>2.8.2</version> 254 </plugin> 255 </plugins> 256 </pluginManagement> 257 258 </build> 259 </project>
二,相关配置文件(对照上面的项目结构图,放在对应的Folder)
1.jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dirverUrl=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.password=123456
#初始连接大小
druid.initialSize=5
#最大连接数
druid.maxActive=100
#最小空闲数
druid.minIdle=5
#最大等待时间,单位为ms
druid.manWait=60000
2.redis.properties
#服务器ip
redis.hostname=127.0.0.1
#redis数据库端口
redis.port=6379
#使用的数据库(共有16个数据库 0~15)
redis.database=2
#控制一个pool可分配多少个jedis实例,
redis.pool.maxActive=50
#控制一个pool最多有多少个状态为idle的jedis实例;
redis.pool.maxIdle=300
#最大等待连接时间(单位毫秒)
redis.pool.maxTotal=600
#redis密码(一般不设密码,设了重启服务也会没有)
redis.pass=
3.spring.web.xml (控制层配置文件,springmvc)。
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" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 11 12 <!-- 配置SpringMVC --> 13 <!-- 1.开启SpringMVC注解模式 --> 14 <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 15 (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> 16 <mvc:annotation-driven/> 17 18 <mvc:default-servlet-handler/> 19 20 <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> 21 <mvc:resources mapping="/resources/**" location="/resources/"/> 22 23 <!-- 3.定义视图解析器 --> 24 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 25 <property name="prefix" value="/WEB-INF/page/"></property> 26 <property name="suffix" value=".jsp"></property> 27 </bean> 28 29 <!--4.上传文件解析器--> 30 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 31 <property name="defaultEncoding" value="utf-8"></property> 32 <property name="maxUploadSize" value="10485760000"></property><!-- 最大上传文件大小 --> 33 <property name="maxInMemorySize" value="10960"></property> 34 </bean> 35 36 <!-- 在spring-mvc.xml文件中加入这段配置后,spring返回给页面的都是utf-8编码了 --> 37 <bean 38 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 39 <property name="messageConverters"> 40 <list> 41 <bean 42 class="org.springframework.http.converter.StringHttpMessageConverter"> 43 <property name="supportedMediaTypes"> 44 <list> 45 <value>text/html;charset=UTF-8</value> 46 </list> 47 </property> 48 </bean> 49 </list> 50 </property> 51 </bean> 52 53 <!--扫描web相关的bean--> 54 <context:component-scan base-package="indi.lwc.redis.web"/> 55 </beans>
4.spring-dao.xml (持久层dao层配置文件,mybatis)
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:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd"> 12 13 <!-- 配置整合mybatis过程 --> 14 <!-- 1.配置数据库相关参数properties的属性:${url} --> 15 <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> 16 17 <!--数据库连接池--> 18 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 19 <!-- 配置连接池属性 --> 20 <property name="driverClass" value="${jdbc.driverClassName}" /> 21 <property name="jdbcUrl" value="${jdbc.dirverUrl}" /> 22 <property name="user" value="${jdbc.user}" /> 23 <property name="password" value="${jdbc.password}" /> 24 25 <!-- c3p0连接池的私有属性 --> 26 <property name="initialPoolSize" value="${druid.initialSize}"/> 27 <property name="maxPoolSize" value="${druid.maxActive}" /> 28 <property name="minPoolSize" value="${druid.minIdle}" /> 29 <!-- 关闭连接后不自动commit --> 30 <property name="autoCommitOnClose" value="false" /> 31 <!-- 获取连接超时时间 --> 32 <property name="checkoutTimeout" value="${druid.manWait}" /> 33 <!-- 当获取连接失败重试次数 --> 34 <property name="acquireRetryAttempts" value="2" /> 35 </bean> 36 37 <!--配置sqlSe--> 38 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 39 <!--配置数据库连接词--> 40 <property name="dataSource" ref="dataSource"/> 41 <!--配置mybatis全局配置文件--> 42 <property name="configLocation" value="classpath:mybatis.xml"/> 43 <!--扫描bean使用别名--> 44 <property name="typeAliasesPackage" value="indi.lwc.redis.bean"/> 45 <!--扫描映射文件--> 46 <property name="mapperLocations" value="classpath:mapper/*.xml"/> 47 </bean> 48 49 <!--4.配置扫描dao接口包,动态实现dao接口,注入到spring容器中--> 50 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 51 <!--注入sqlSessionFactory--> 52 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 53 <!--给出需要扫描的dao接口包--> 54 <property name="basePackage" value="indi.lwc.redis.dao"/> 55 </bean> 56 57 58 </beans>
5.spring-service.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:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd"> 12 13 <!--扫描service包下的所有注解--> 14 <context:component-scan base-package="indi.lwc.redis.service"/> 15 16 <!--配置事务管理器--> 17 <bean id="transactionManager" 18 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 19 <!--注入数据库连接池--> 20 <property name="dataSource" ref="dataSource"/> 21 </bean> 22 23 <!--配置基于注解的声明式事务--> 24 <tx:annotation-driven transaction-manager="transactionManager"/> 25 26 27 </beans>
6.spring-redis.xml (配置redis相关类,如RedisTemplate,JedisPoolConfig等)
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 5 http://www.springframework.org/schema/context 6 http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 7 <description>redis相关类 spring托管</description> 8 9 <!--载入配置文件--> 10 <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/> 11 12 <!--配置JedisPoolConfig 实例--> 13 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 14 <property name="maxIdle" value="${redis.pool.maxIdle}"/> 15 <property name="maxTotal" value="${redis.pool.maxTotal}"/> 16 </bean> 17 18 <!--配置jedisConnectionFactory--> 19 <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 20 <property name="hostName" value="${redis.hostname}"/> 21 <property name="port" value="${redis.port}"/> 22 <property name="password" value="${redis.pass}"/> 23 <property name="database" value="${redis.database}"/> 24 <property name="poolConfig" ref="poolConfig"/> 25 </bean> 26 27 <!--配置RedisTemplate--> 28 <bean id="rediTeplate" class="indi.lwc.redis.cache.RedisConfg"> 29 <constructor-arg ref="jedisConnectionFactory"/> 30 </bean> 31 32 33 </beans>
7.mybatis.xml (mybatis全局配置文件)
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!--配置全局配置--> 7 <settings> 8 <!----> 9 <setting name="cacheEnabled" value="false"/> 10 <!--打印查询语句--> 11 <setting name="logImpl" value="STDOUT_LOGGING"/> 12 <!--使用jdbc的getGeneratedKeys获取数据库自增主键值--> 13 <setting name="useGeneratedKeys" value="true"/> 14 <!--使用列别名替换列名字 默认true--> 15 <setting name="useColumnLabel" value="true"/> 16 <!--开启驼峰命名转换:Table{create_time} Entity{createTime} --> 17 <setting name="mapUnderscoreToCamelCase" value="true"/> 18 </settings> 19 </configuration>
8.web.xml配置 (通常会自动生成,在webapp/web-inf下面)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 7 <!-- 配置DispatcherServlet --> 8 <servlet> 9 <servlet-name>seckill-dispatcher</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置springMVC需要加载的配置文件 spring-com.ht.dao.xml,spring-service.xml,spring-web.xml 12 Mybatis - > spring -> springmvc --> 13 <init-param> 14 <param-name>contextConfigLocation</param-name> 15 <param-value>classpath:spring/spring-*.xml</param-value> 16 </init-param> 17 </servlet> 18 19 <servlet-mapping> 20 <servlet-name>seckill-dispatcher</servlet-name> 21 <!-- 默认匹配所有的请求 --> 22 <url-pattern>/</url-pattern> 23 </servlet-mapping> 24 25 26 </web-app>
三,需要的相关类文件(对照最上面的项目结构图,放在对应的包内)
1.RedisConfig.java (redis对象序列化类,你要存对象就必须配置。因为redis支持的数据类型只有 String,hash,List,Set,zset) 放在cache包下面。
1 package indi.lwc.redis.cache; 2 3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.PropertyAccessor; 5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 import org.springframework.data.redis.connection.RedisConnectionFactory; 9 import org.springframework.data.redis.core.RedisTemplate; 10 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 11 import org.springframework.data.redis.serializer.StringRedisSerializer; 12 13 /** 14 * 如果我们想使用RedisTemplate存取对象, 15 * 那我们只要设置对应的序列器就行了 16 */ 17 @Configuration 18 public class RedisConfg { 19 20 private RedisConnectionFactory redisConnectionFactory; 21 22 23 public RedisConfg(RedisConnectionFactory redisConnectionFactory){ 24 this.redisConnectionFactory=redisConnectionFactory; 25 } 26 /** 27 * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 28 * 29 * @return 30 */ 31 @Bean 32 public RedisTemplate<Object, Object> redisTemplate() { 33 RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); 34 redisTemplate.setConnectionFactory(redisConnectionFactory); 35 36 // 使用Jackson2JsonRedisSerialize 替换默认序列化 37 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 38 39 ObjectMapper objectMapper = new ObjectMapper(); 40 objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 41 objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 42 43 jackson2JsonRedisSerializer.setObjectMapper(objectMapper); 44 45 // 设置value的序列化规则和 key的序列化规则 46 redisTemplate.setKeySerializer(new StringRedisSerializer()); 47 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 48 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 49 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); 50 redisTemplate.afterPropertiesSet(); 51 return redisTemplate; 52 } 53 54 }
2,Emp.java (实体类) 放在bean包下。
1 package indi.lwc.redis.bean; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 6 public class Emp implements Serializable { 7 private Integer eno; 8 private String ename; 9 private String esex; 10 private float sal; 11 private Integer dno; 12 private Date join_date; 13 private Integer elevel; 14 private String password; 15 16 17 public Integer getEno() { 18 return eno; 19 } 20 21 public void setEno(Integer eno) { 22 this.eno = eno; 23 } 24 25 public String getEname() { 26 return ename; 27 } 28 29 public void setEname(String ename) { 30 this.ename = ename; 31 } 32 33 public String getEsex() { 34 return esex; 35 } 36 37 public void setEsex(String esex) { 38 this.esex = esex; 39 } 40 41 public float getSal() { 42 return sal; 43 } 44 45 public void setSal(float sal) { 46 this.sal = sal; 47 } 48 49 public Integer getDno() { 50 return dno; 51 } 52 53 public void setDno(Integer dno) { 54 this.dno = dno; 55 } 56 57 public Date getJoin_date() { 58 return join_date; 59 } 60 61 public void setJoin_date(Date join_date) { 62 this.join_date = join_date; 63 } 64 65 public Integer getElevel() { 66 return elevel; 67 } 68 69 public void setElevel(Integer elevel) { 70 this.elevel = elevel; 71 } 72 73 public String getPassword() { 74 return password; 75 } 76 77 public void setPassword(String password) { 78 this.password = password; 79 } 80 81 @Override 82 public String toString() { 83 return "Emp{" + 84 "eno=" + eno + 85 ", ename='" + ename + '\'' + 86 ", esex='" + esex + '\'' + 87 ", sal=" + sal + 88 ", dno=" + dno + 89 ", join_date=" + join_date + 90 ", elevel=" + elevel + 91 ", password='" + password + '\'' + 92 '}'; 93 } 94 }
3.EmpDao.interface 放在dao包下。
1 package indi.lwc.redis.dao; 2 3 import indi.lwc.redis.bean.Emp; 4 5 public interface EmpDao { 6 7 8 /** 9 * 根据id查询用户 10 * @return 11 */ 12 Emp queryEmpById(Integer eId); 13 14 /** 15 * 更新员工 16 * @param emp 17 * @return 18 */ 19 int updateEmp(Emp emp); 20 21 /** 22 *删除指定id 23 * @param eId 24 * @return 25 */ 26 int deleteEmp(Integer eId); 27 28 /** 29 * 添加员工 30 * @param emp 31 * @return 32 */ 33 int insertEmp(Emp emp); 34 }
4.EmpDao.xml 放在mapper包下
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="indi.lwc.redis.dao.EmpDao"> 6 <select id="queryEmpById" resultType="indi.lwc.redis.bean.Emp"> 7 select * from emp where eno=#{eId} 8 </select> 9 <update id="updateEmp" parameterType="indi.lwc.redis.bean.Emp"> 10 update emp 11 <set> 12 <if test="ename!=null"> 13 ename=#{ename}, 14 </if> 15 <if test="esex!=null"> 16 esex=#{esex}, 17 </if> 18 <if test="sal!=null and sal!=0.0"> 19 sal=#{sal}, 20 </if> 21 <if test="dno!=null"> 22 dno=#{dno}, 23 </if> 24 <if test="join_date!=null"> 25 join_date=#{join_date}, 26 </if> 27 <if test="elevel!=null and elevel!=0"> 28 elevel=#{elevel}, 29 </if> 30 <if test="password!=null"> 31 password=#{password} 32 </if> 33 </set> 34 where eno=#{eno} 35 </update> 36 <delete id="deleteEmp"> 37 delete from emp where eno=#{eId} 38 </delete> 39 <insert id="insertEmp"> 40 <selectKey keyColumn="eno" keyProperty="eno" resultType="int" order="AFTER"> 41 select last_insert_id() 42 </selectKey> 43 insert into emp(ename,esex,sal,dno,join_date,elevel,password) VALUE 44 (#{ename},#{esex},#{sal},#{dno},#{join_date},#{elevel},#{password}) 45 </insert> 46 </mapper>
5.EmpService.Interface 放在sercie包下
1 package indi.lwc.redis.service; 2 3 import indi.lwc.redis.bean.Emp; 4 5 public interface EmpService { 6 7 8 /** 9 * 根据id查询emp 10 * @param eId 11 * @return 12 */ 13 Emp findEmpById(int eId); 14 15 16 /** 17 * 更新员工信息 18 * @param emp 19 * @return 20 */ 21 Emp replaceEmp(Emp emp); 22 23 /** 24 * 删除员工信息 25 * @param eId 26 * @return 27 */ 28 int removeEmp(int eId); 29 30 /** 31 * 添加员工 32 * @param emp 33 * @return 34 */ 35 Emp addEmp(Emp emp); 36 }
6.EmpServiceImpl.java (逻辑处理类,redis的存取操作也在这个类)
1 package indi.lwc.redis.service.impl; 2 3 import indi.lwc.redis.bean.Emp; 4 import indi.lwc.redis.dao.EmpDao; 5 import indi.lwc.redis.service.EmpService; 6 import indi.lwc.redis.util.RedisTemplateUtil; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.cglib.beans.BeanMap; 9 import org.springframework.data.redis.core.HashOperations; 10 import org.springframework.data.redis.core.RedisTemplate; 11 import org.springframework.data.redis.core.ValueOperations; 12 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 13 import org.springframework.stereotype.Service; 14 15 16 import javax.annotation.Resource; 17 import java.io.ByteArrayOutputStream; 18 import java.io.IOException; 19 import java.io.ObjectOutputStream; 20 import java.util.HashMap; 21 import java.util.List; 22 import java.util.Map; 23 24 @Service 25 public class EmpServiceImpl implements EmpService { 26 27 @Resource 28 private EmpDao empDao; 29 30 @Autowired 31 private RedisTemplate redisTemplate; 32 33 @Override 34 public Emp findEmpById(int eId) { 35 ValueOperations valueOperations = redisTemplate.opsForValue(); 36 RedisTemplateUtil redisTemplateUtil =new RedisTemplateUtil(redisTemplate); 37 //key 38 String empName ="emp_"+eId; 39 Emp emp = null; 40 if (redisTemplateUtil.get(empName)!=null && !"".equals(redisTemplateUtil.get(empName))){ 41 System.out.println("缓存中查询"); 42 //从缓存中取出 43 emp =(Emp) redisTemplateUtil.get(empName); 44 }else { 45 HashOperations hashOperations = redisTemplate.opsForHash(); 46 System.out.println("数据中查"); 47 emp = empDao.queryEmpById(eId); 48 //存入缓存 49 redisTemplateUtil.set(empName,emp); 50 } 51 52 return emp; 53 } 54 55 @Override 56 public Emp replaceEmp(Emp emp) { 57 empDao.updateEmp(emp); 58 return emp; 59 } 60 61 @Override 62 public int removeEmp(int eId) { 63 return empDao.deleteEmp(eId); 64 } 65 66 @Override 67 public Emp addEmp(Emp emp) { 68 empDao.insertEmp(emp); 69 return emp; 70 } 71 72 /** 73 * 将对象属性转化为map结合 74 */ 75 public static <T> Map<String, Object> beanToMap(T bean) { 76 Map<String, Object> map = new HashMap<>(); 77 if (bean != null) { 78 BeanMap beanMap = BeanMap.create(bean); 79 for (Object key : beanMap.keySet()) { 80 map.put(key+"", beanMap.get(key)); 81 } 82 } 83 return map; 84 } 85 86 87 /** 88 * 将map集合中的数据转化为指定对象的同名属性中 89 */ 90 public static <T> T mapToBean(Map<String, Object> map,Class<T> clazz) throws Exception { 91 T bean = clazz.newInstance(); 92 BeanMap beanMap = BeanMap.create(bean); 93 beanMap.putAll(map); 94 return bean; 95 } 96 97 98 }
7.RedisTemplateUtil.java (RedisTemplate各大成员内的api方法较多,所以我们通常将String,list,hash,set,zset 等数据类型的基本方法封装起来)
1 package indi.lwc.redis.util; 2 3 import org.springframework.data.redis.core.RedisTemplate; 4 import org.springframework.data.redis.core.ValueOperations; 5 6 import java.util.List; 7 import java.util.Map; 8 import java.util.Set; 9 10 public class RedisTemplateUtil { 11 12 private RedisTemplate redisTemplate; 13 14 public RedisTemplateUtil(RedisTemplate redisTemplate){ 15 this.redisTemplate = redisTemplate; 16 } 17 18 //将多种类型的值存入缓存 19 public void set(String key, Object value){ 20 ValueOperations valueOperations = redisTemplate.opsForValue(); 21 valueOperations.set(key,value); 22 } 23 24 //获取指定的key值 25 public Object get(String key){ 26 return redisTemplate.opsForValue().get(key); 27 } 28 29 //将list存入缓存 30 public void setList(String key, List value){ 31 redisTemplate.opsForList().leftPush(key,value); 32 } 33 34 //获取指定key的list值 35 public Object getList(String key){ 36 return redisTemplate.opsForList().leftPop(key); 37 } 38 39 //将set存入缓存 40 public void setSet(String key, Set value){ 41 redisTemplate.opsForSet().add(key,value); 42 } 43 44 //获取set 45 public Object getSet(String key){ 46 return redisTemplate.opsForSet().members(key); 47 } 48 49 //将map存入缓存 50 public void setHash(String key , Map value){ 51 redisTemplate.opsForHash().putAll(key,value); 52 } 53 54 //获取map 55 public Object getHash(String key){ 56 return redisTemplate.opsForHash().entries(key); 57 } 58 59 //删除某个key 60 public void delete(String key){ 61 redisTemplate.delete(key); 62 } 63 64 }
8.BaseTest.java (启动配置)
1 package indi.lwc.test; 2 3 import org.junit.runner.RunWith; 4 import org.springframework.test.context.ContextConfiguration; 5 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 7 @RunWith(SpringJUnit4ClassRunner.class) 8 @ContextConfiguration( 9 {"classpath:spring/spring-redis.xml", 10 "classpath:spring/spring-service.xml", 11 "classpath:spring/spring-dao.xml"}) 12 public class BaseTest { 13 14 15 }
9.RedisTest.java (测试类)
1 package indi.lwc.test; 2 3 import indi.lwc.redis.bean.Emp; 4 import indi.lwc.redis.service.EmpService; 5 import org.junit.Assert; 6 import org.junit.Test; 7 8 import javax.annotation.Resource; 9 10 public class RedisTest extends BaseTest { 11 12 @Resource 13 private EmpService empService; 14 15 16 @Test 17 public void testFindEmpById(){ 18 Emp emp = empService.findEmpById(2); 19 System.out.println(emp.toString()); 20 } 21 22 23 24 25 }
Spring Cache注解
除了使用redisTemplate内置api实现缓存操作以外,我们还可以使用spring自带Cache注解来实现缓存操作。
缓存一般使用在服务层,在你想缓存的方法上添加相应的注解。下面介绍3个常用的注解。
@Cacheable
spring 会在其被调用后将返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。
@CachePut
标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CacheEvict
用来标注在需要清除缓存元素的方法或类上的。