SSM 整合Redis緩存數據庫 + RedisTemplate對象的使用,Spring Cache註解的使用 (第三章)

SSM項目架構搭建

     

 

 

  該圖是一個搭建好了的SSM項目結構,用maven管理項目依賴。html

  一,添加項目依賴(我直接貼pom.xml文件了)java

    

 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.propertiesmysql

       

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.propertiesgit

 

#服務器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)。github

    

 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層配置文件,mybatisweb

    

 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 (服務層配置文件,處理邏輯,減小耦合層)。redis

  

 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等spring

    

 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全局配置文件sql

 

 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

          用來標註在須要清除緩存元素的方法或類上的。

相關文章
相關標籤/搜索