mybatis整合Redis实现二级缓存
-
mybatis整合ehcache作为缓存
* mybatis整合Redis
1.为什么需要缓存
拉高程序的性能
2. 什么样的数据需要缓存
很少被修改或根本不改的数据
mybatis整合ehcache作为缓存
导入相关依赖
pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342 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>com.li</groupId>
8 <artifactId>ssm</artifactId>
9 <version>1.0-SNAPSHOT</version>
10 <packaging>war</packaging>
11
12 <name>ssm Maven Webapp</name>
13 <!-- FIXME change it to the project's website -->
14 <url>http://www.example.com</url>
15
16 <properties>
17 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18 <maven.compiler.source>1.8</maven.compiler.source>
19 <maven.compiler.target>1.8</maven.compiler.target>
20 <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
21
22 <!--添加jar包依赖-->
23 <!--1.spring 5.0.2.RELEASE相关-->
24 <spring.version>5.0.2.RELEASE</spring.version>
25 <!--2.mybatis相关-->
26 <mybatis.version>3.4.5</mybatis.version>
27 <!--mysql-->
28 <mysql.version>5.1.44</mysql.version>
29 <!--pagehelper分页jar依赖-->
30 <pagehelper.version>5.1.2</pagehelper.version>
31 <!--mybatis与spring集成jar依赖-->
32 <mybatis.spring.version>1.3.1</mybatis.spring.version>
33 <!--3.dbcp2连接池相关 druid-->
34 <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
35 <commons.pool2.version>2.4.3</commons.pool2.version>
36 <!--4.log日志相关-->
37 <log4j2.version>2.9.1</log4j2.version>
38 <!--5.其他-->
39 <junit.version>4.12</junit.version>
40 <servlet.version>4.0.0</servlet.version>
41 <lombok.version>1.18.2</lombok.version>
42
43 <!-- log4j2日志配置相关依赖 -->
44 <log4j2.version>2.9.1</log4j2.version>
45 <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
46 <slf4j.version>1.7.13</slf4j.version>
47 <!-- redis与spring的整合依赖 -->
48 <redis.version>2.9.0</redis.version>
49 <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
50 <!-- jackson -->
51 <jackson.version>2.9.3</jackson.version>
52
53 </properties>
54
55 <dependencies>
56 <!--1.spring相关-->
57 <dependency>
58 <groupId>org.springframework</groupId>
59 <artifactId>spring-context</artifactId>
60 <version>${spring.version}</version>
61 </dependency>
62 <dependency>
63 <groupId>org.springframework</groupId>
64 <artifactId>spring-orm</artifactId>
65 <version>${spring.version}</version>
66 </dependency>
67 <dependency>
68 <groupId>org.springframework</groupId>
69 <artifactId>spring-tx</artifactId>
70 <version>${spring.version}</version>
71 </dependency>
72 <dependency>
73 <groupId>org.springframework</groupId>
74 <artifactId>spring-aspects</artifactId>
75 <version>${spring.version}</version>
76 </dependency>
77 <dependency>
78 <groupId>org.springframework</groupId>
79 <artifactId>spring-web</artifactId>
80 <version>${spring.version}</version>
81 </dependency>
82 <dependency>
83 <groupId>org.springframework</groupId>
84 <artifactId>spring-test</artifactId>
85 <version>${spring.version}</version>
86 </dependency>
87 <!--2.mybatis相关-->
88 <dependency>
89 <groupId>org.mybatis</groupId>
90 <artifactId>mybatis</artifactId>
91 <version>${mybatis.version}</version>
92 </dependency>
93 <!--mysql-->
94 <dependency>
95 <groupId>mysql</groupId>
96 <artifactId>mysql-connector-java</artifactId>
97 <version>${mysql.version}</version>
98 </dependency>
99 <!--pagehelper分页插件jar包依赖-->
100 <dependency>
101 <groupId>com.github.pagehelper</groupId>
102 <artifactId>pagehelper</artifactId>
103 <version>${pagehelper.version}</version>
104 </dependency>
105 <!--mybatis与spring集成jar包依赖-->
106 <dependency>
107 <groupId>org.mybatis</groupId>
108 <artifactId>mybatis-spring</artifactId>
109 <version>${mybatis.spring.version}</version>
110 </dependency>
111 <!--3.dbcp2连接池相关-->
112 <dependency>
113 <groupId>org.apache.commons</groupId>
114 <artifactId>commons-dbcp2</artifactId>
115 <version>${commons.dbcp2.version}</version>
116 </dependency>
117 <dependency>
118 <groupId>org.apache.commons</groupId>
119 <artifactId>commons-pool2</artifactId>
120 <version>${commons.pool2.version}</version>
121 </dependency>
122 <!--4.log日志相关依赖-->
123 <!--核心log4j2jar包-->
124 <dependency>
125 <groupId>org.apache.logging.log4j</groupId>
126 <artifactId>log4j-core</artifactId>
127 <version>${log4j2.version}</version>
128 </dependency>
129 <dependency>
130 <groupId>org.apache.logging.log4j</groupId>
131 <artifactId>log4j-api</artifactId>
132 <version>${log4j2.version}</version>
133 </dependency>
134 <!--web工程需要包含log4j-web,非web工程不需要-->
135 <dependency>
136 <groupId>org.apache.logging.log4j</groupId>
137 <artifactId>log4j-web</artifactId>
138 <version>${log4j2.version}</version>
139 </dependency>
140 <!--5.其他-->
141 <dependency>
142 <groupId>junit</groupId>
143 <artifactId>junit</artifactId>
144 <version>${junit.version}</version>
145 <scope>test</scope>
146 </dependency>
147 <dependency>
148 <groupId>javax.servlet</groupId>
149 <artifactId>javax.servlet-api</artifactId>
150 <version>${servlet.version}</version>
151 <scope>provided</scope>
152 </dependency>
153 <dependency>
154 <groupId>org.projectlombok</groupId>
155 <artifactId>lombok</artifactId>
156 <version>${lombok.version}</version>
157 <scope>provided</scope>
158 </dependency>
159
160
161 <dependency>
162 <groupId>org.springframework</groupId>
163 <artifactId>spring-context-support</artifactId>
164 <version>${spring.version}</version>
165 </dependency>
166
167 <!--mybatis与ehcache整合-->
168 <dependency>
169 <groupId>org.mybatis.caches</groupId>
170 <artifactId>mybatis-ehcache</artifactId>
171 <version>1.1.0</version>
172 </dependency>
173
174
175
176 <!--ehcache依赖-->
177 <dependency>
178 <groupId>net.sf.ehcache</groupId>
179 <artifactId>ehcache</artifactId>
180 <version>2.10.0</version>
181 </dependency>
182
183 <!-- log4j2日志相关依赖 -->
184 <!-- log配置:Log4j2 + Slf4j -->
185 <!-- slf4j核心包-->
186 <dependency>
187 <groupId>org.slf4j</groupId>
188 <artifactId>slf4j-api</artifactId>
189 <version>${slf4j.version}</version>
190 </dependency>
191 <dependency>
192 <groupId>org.slf4j</groupId>
193 <artifactId>jcl-over-slf4j</artifactId>
194 <version>${slf4j.version}</version>
195 <scope>runtime</scope>
196 </dependency>
197
198 <!--核心log4j2jar包-->
199 <dependency>
200 <groupId>org.apache.logging.log4j</groupId>
201 <artifactId>log4j-api</artifactId>
202 <version>${log4j2.version}</version>
203 </dependency>
204 <dependency>
205 <groupId>org.apache.logging.log4j</groupId>
206 <artifactId>log4j-core</artifactId>
207 <version>${log4j2.version}</version>
208 </dependency>
209 <!--用于与slf4j保持桥接-->
210 <dependency>
211 <groupId>org.apache.logging.log4j</groupId>
212 <artifactId>log4j-slf4j-impl</artifactId>
213 <version>${log4j2.version}</version>
214 </dependency>
215 <!--web工程需要包含log4j-web,非web工程不需要-->
216 <dependency>
217 <groupId>org.apache.logging.log4j</groupId>
218 <artifactId>log4j-web</artifactId>
219 <version>${log4j2.version}</version>
220 <scope>runtime</scope>
221 </dependency>
222
223 <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
224 <dependency>
225 <groupId>com.lmax</groupId>
226 <artifactId>disruptor</artifactId>
227 <version>${log4j2.disruptor.version}</version>
228 </dependency>
229
230 <dependency>
231 <groupId>redis.clients</groupId>
232 <artifactId>jedis</artifactId>
233 <version>${redis.version}</version>
234 </dependency>
235 <dependency>
236 <groupId>org.springframework.data</groupId>
237 <artifactId>spring-data-redis</artifactId>
238 <version>${redis.spring.version}</version>
239 </dependency>
240
241 <!-- jackson -->
242 <dependency>
243 <groupId>com.fasterxml.jackson.core</groupId>
244 <artifactId>jackson-databind</artifactId>
245 <version>${jackson.version}</version>
246 </dependency>
247 <dependency>
248 <groupId>com.fasterxml.jackson.core</groupId>
249 <artifactId>jackson-core</artifactId>
250 <version>${jackson.version}</version>
251 </dependency>
252 <dependency>
253 <groupId>com.fasterxml.jackson.core</groupId>
254 <artifactId>jackson-annotations</artifactId>
255 <version>${jackson.version}</version>
256 </dependency>
257
258 </dependencies>
259
260 <build>
261 <finalName>ssm</finalName>
262 <resources>
263 <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
264 <resource>
265 <directory>src/main/java</directory>
266 <includes>
267 <include>**/*.xml</include>
268 </includes>
269 </resource>
270 <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
271 <resource>
272 <directory>src/main/resources</directory>
273 <includes>
274 <include>*.properties</include>
275 <include>*.xml</include>
276 </includes>
277 </resource>
278 </resources>
279 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
280 <plugins>
281 <plugin>
282 <groupId>org.apache.maven.plugins</groupId>
283 <artifactId>maven-compiler-plugin</artifactId>
284 <version>${maven.compiler.plugin.version}</version>
285 <configuration>
286 <source>${maven.compiler.source}</source>
287 <target>${maven.compiler.target}</target>
288 <encoding>${project.build.sourceEncoding}</encoding>
289 </configuration>
290 </plugin>
291 <plugin>
292 <groupId>org.mybatis.generator</groupId>
293 <artifactId>mybatis-generator-maven-plugin</artifactId>
294 <version>1.3.2</version>
295 <dependencies>
296 <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
297 <dependency>
298 <groupId>mysql</groupId>
299 <artifactId>mysql-connector-java</artifactId>
300 <version>${mysql.version}</version>
301 </dependency>
302 </dependencies>
303 <configuration>
304 <overwrite>true</overwrite>
305 </configuration>
306 </plugin>
307 <plugin>
308 <artifactId>maven-clean-plugin</artifactId>
309 <version>3.1.0</version>
310 </plugin>
311 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
312 <plugin>
313 <artifactId>maven-resources-plugin</artifactId>
314 <version>3.0.2</version>
315 </plugin>
316 <plugin>
317 <artifactId>maven-compiler-plugin</artifactId>
318 <version>3.8.0</version>
319 </plugin>
320 <plugin>
321 <artifactId>maven-surefire-plugin</artifactId>
322 <version>2.22.1</version>
323 </plugin>
324 <plugin>
325 <artifactId>maven-war-plugin</artifactId>
326 <version>3.2.2</version>
327 </plugin>
328 <plugin>
329 <artifactId>maven-install-plugin</artifactId>
330 <version>2.5.2</version>
331 </plugin>
332 <plugin>
333 <artifactId>maven-deploy-plugin</artifactId>
334 <version>2.8.2</version>
335 </plugin>
336 </plugins>
337 </pluginManagement>
338 </build>
339</project>
340
341
342
在Resource中添加一个ehcache.xml的配置文件
ehcache.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 1<?xml version="1.0" encoding="UTF-8"?>
2<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
4 updateCheck="false">
5 <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
6 <!--path:指定在硬盘上存储对象的路径-->
7 <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
8 <diskStore path="java.io.tmpdir"/>
9
10
11 <!--defaultCache:默认的管理策略-->
12 <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
13 <!--maxElementsInMemory:在内存中缓存的element的最大数目-->
14 <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
15 <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
16 <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
17 <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
18 <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
19 <!--FIFO:first in first out (先进先出)-->
20 <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
21 <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
22 <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
23 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
24
25
26 <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
27 <cache name="stuCache" eternal="false" maxElementsInMemory="100"
28 overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
29 timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
30</ehcache>
31
32
applicationContext-ehcache.xml 这是spring整合MyBatis 相关的配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 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 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5
6 <!-- 使用ehcache缓存 -->
7 <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
8 <property name="configLocation" value="classpath:ehcache.xml"/>
9 <property name="shared" value="true"></property>
10 </bean>
11 <!-- 默认是cacheManager -->
12 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
13 <property name="cacheManager" ref="cacheManagerFactory"/>
14 </bean>
15</beans>
16
17
在applicationContext-mybatis.xml中加入ehcache的配置
相关配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1<!--设置mybaits对缓存的支持-->
2 <property name="configurationProperties">
3 <props>
4 <!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
5 <prop key="cacheEnabled">true</prop>
6 <!-- 查询时,关闭关联对象即时加载以提高性能 -->
7 <prop key="lazyLoadingEnabled">false</prop>
8 <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
9 <prop key="aggressiveLazyLoading">true</prop>
10 </props>
11 </property>
12
13
14
applicationContext.-mybatis.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 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" xmlns:tx="http://www.springframework.org/schema/tx"
5 xmlns:aop="http://www.springframework.org/schema/aop"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
7 <!--1. 注解式开发 -->
8 <!-- 注解驱动 -->
9 <context:annotation-config/>
10 <!-- 用注解方式注入bean,并指定查找范围:com.javaxl.ssm及子子孙孙包-->
11 <context:component-scan base-package="com.li"/>
12<!-- 引入外部jdbc配置文件-->
13 <context:property-placeholder location="classpath:jdbc.properties"/>
14
15 <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
16 destroy-method="close">
17 <property name="driverClassName" value="${jdbc.driver}"/>
18 <property name="url" value="${jdbc.url}"/>
19 <property name="username" value="${jdbc.username}"/>
20 <property name="password" value="${jdbc.password}"/>
21 <!--初始连接数-->
22 <property name="initialSize" value="10"/>
23 <!--最大活动连接数-->
24 <property name="maxTotal" value="100"/>
25 <!--最大空闲连接数-->
26 <property name="maxIdle" value="50"/>
27 <!--最小空闲连接数-->
28 <property name="minIdle" value="10"/>
29 <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。-->
30 <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常-->
31 <property name="maxWaitMillis" value="-1"/>
32 </bean>
33
34 <!--4. spring和MyBatis整合 -->
35 <!--1) 创建sqlSessionFactory-->
36 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
37 <!-- 指定数据源 -->
38 <property name="dataSource" ref="dataSource"/>
39 <!-- 自动扫描XxxMapping.xml文件,**任意路径 -->
40 <property name="mapperLocations" value="classpath*:com/li/**/mapper/*.xml"/>
41 <!-- 指定别名 -->
42 <property name="typeAliasesPackage" value="com/li/**/model"/>
43
44
45
46 <!--设置mybaits对缓存的支持-->
47 <property name="configurationProperties">
48 <props>
49 <!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
50 <prop key="cacheEnabled">true</prop>
51 <!-- 查询时,关闭关联对象即时加载以提高性能 -->
52 <prop key="lazyLoadingEnabled">false</prop>
53 <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
54 <prop key="aggressiveLazyLoading">true</prop>
55 </props>
56 </property>
57
58 <!--配置pagehelper插件-->
59 <property name="plugins">
60 <array>
61 <bean class="com.github.pagehelper.PageInterceptor">
62 <property name="properties">
63 <value>
64 helperDialect=mysql
65 </value>
66 </property>
67 </bean>
68 </array>
69 </property>
70 </bean>
71
72 <!--2) 自动扫描com/javaxl/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,-->
73 <!-- 即可直接在程序中使用dao接口,不用再获取sqlsession对象-->
74 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
75 <!--basePackage 属性是映射器接口文件的包路径。-->
76 <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径-->
77 <property name="basePackage" value="com/li/**/mapper"/>
78 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
79 </bean>
80
81 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
82 <property name="dataSource" ref="dataSource" />
83 </bean>
84 <tx:annotation-driven transaction-manager="transactionManager" />
85<!-- 开启动态代理-->
86 <aop:aspectj-autoproxy/>
87</beans>
88
89
然后在Mapper映射的xml中开启二级缓存,这里是BookMapper.xml
加在mapper标签下面第一个即可
1
2
3
4
5
6
7
8
9
10 1<!-- <!--配置ehcache-->-->
2 <cache type="org.mybatis.caches.ehcache.EhcacheCache">
3<!-- <property name="timeToIdleSeconds" value="3600"/>-->
4<!-- <property name="timeToLiveSeconds" value="3600"/>-->
5<!-- <property name="maxEntriesLocalHeap" value="1000"/>-->
6<!-- <property name="maxEntriesLocalDisk" value="10000000"/>-->
7<!-- <property name="memoryStoreEvictionPolicy" value="LRU"/>-->
8 </cache>
9
10
然后还能改变useCache的值来开启和关闭缓存
true和false
然后用JUnit测试一个方法查询同一个数据,开启了后通过日志看到第二次没有执行sql语句了,而是进入缓存取的值
1
2
3
4
5
6
7
8
9 1 @Test
2 public void cacheSimgle() {
3 Book book = this.bookService.selectByPrimaryKey(29);
4 System.out.println(book);
5 Book book1 = this.bookService.selectByPrimaryKey(29);
6 System.out.println(book1);
7 }
8
9
mybatis整合Redis
Redis和ehcache的区别:
ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
redis是通过socket访问到缓存服务,效率比ecache低,比数据库要快很多,处理集群和分布式缓存方便。
所以在数据量比较大的时候显然redis比较合适
整合步骤:
首先依然是导入整合所需pom依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 1<!-- redis与spring的整合依赖 -->
2 <redis.version>2.9.0</redis.version>
3 <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
4
5 <dependency>
6 <groupId>redis.clients</groupId>
7 <artifactId>jedis</artifactId>
8 <version>${redis.version}</version>
9 </dependency>
10 <dependency>
11 <groupId>org.springframework.data</groupId>
12 <artifactId>spring-data-redis</artifactId>
13 <version>${redis.spring.version}</version>
14 </dependency>
15
16
17
log4j和序列化需要的jackson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1<!-- jackson -->
2 <jackson.version>2.9.3</jackson.version>
3
4<!-- jackson -->
5 <dependency>
6 <groupId>com.fasterxml.jackson.core</groupId>
7 <artifactId>jackson-databind</artifactId>
8 <version>${jackson.version}</version>
9 </dependency>
10 <dependency>
11 <groupId>com.fasterxml.jackson.core</groupId>
12 <artifactId>jackson-core</artifactId>
13 <version>${jackson.version}</version>
14 </dependency>
15 <dependency>
16 <groupId>com.fasterxml.jackson.core</groupId>
17 <artifactId>jackson-annotations</artifactId>
18 <version>${jackson.version}</version>
19 </dependency>
20
21
22
23
因为redis是NoSql(非关系型数据库),所以需要连接文件,然后把redis.properties导入
redis.properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1redis.hostName=192.168.183.135
2redis.port=6379
3redis.password=123456
4redis.timeout=10000
5redis.maxIdle=300
6redis.maxTotal=1000
7redis.maxWaitMillis=1000
8redis.minEvictableIdleTimeMillis=300000
9redis.numTestsPerEvictionRun=1024
10redis.timeBetweenEvictionRunsMillis=30000
11redis.testOnBorrow=true
12redis.testWhileIdle=true
13
14
15
然后导入我们的applicationContext-redis.xml文件,因为我们需要在文件中引入我们redis.properties文件又要引入jdbc.properties文件,还有我们桥接redis的工具类
所以需要在我们的applicationContext.xml中添加引入两个或多个属性文件的写法
applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 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" xmlns:tx="http://www.springframework.org/schema/tx"
5 xmlns:aop="http://www.springframework.org/schema/aop"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
7
8<!-- 1. 引入properties配置文件 -->
9 <context:property-placeholder location="classpath:redis.properties,classpath:jdbc.properties" />
10 <!-- 整合mybatis-->
11 <import resource="applicationContext-mybatis.xml"></import>
12 <!-- 整合redis-->
13 <import resource="applicationContext-redis.xml"></import>
14</beans>
15
16
applicatonContext-redis.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70 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 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
6
7 <!-- 1. 引入properties配置文件 -->
8 <!--<context:property-placeholder location="classpath:redis.properties" />-->
9
10 <!-- 2. redis连接池配置-->
11 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
12 <!--最大空闲数-->
13 <property name="maxIdle" value="${redis.maxIdle}"/>
14 <!--连接池的最大数据库连接数 -->
15 <property name="maxTotal" value="${redis.maxTotal}"/>
16 <!--最大建立连接等待时间-->
17 <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
18 <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
19 <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
20 <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
21 <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
22 <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
23 <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
24 <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
25 <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
26 <!--在空闲时检查有效性, 默认false -->
27 <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
28 </bean>
29
30 <!-- 3. redis连接工厂 -->
31 <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
32 destroy-method="destroy">
33 <property name="poolConfig" ref="poolConfig"/>
34 <!--IP地址 -->
35 <property name="hostName" value="${redis.hostName}"/>
36 <!--端口号 -->
37 <property name="port" value="${redis.port}"/>
38 <!--如果Redis设置有密码 -->
39 <property name="password" value="${redis.password}"/>
40 <!--客户端超时时间单位是毫秒 -->
41 <property name="timeout" value="${redis.timeout}"/>
42 </bean>
43
44 <!-- 4. redis操作模板,使用该对象可以操作redis -->
45 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
46 <property name="connectionFactory" ref="connectionFactory"/>
47 <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
48 <property name="keySerializer">
49 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
50 </property>
51 <property name="valueSerializer">
52 <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
53 </property>
54 <property name="hashKeySerializer">
55 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
56 </property>
57 <property name="hashValueSerializer">
58 <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
59 </property>
60 <!--开启事务 -->
61 <property name="enableTransactionSupport" value="true"/>
62 </bean>
63
64 <!-- 5.使用中间类解决RedisCache.RedisTemplate的静态注入,从而使MyBatis实现第三方缓存 -->
65 <bean id="redisCacheTransfer" class="com.li.util.RedisCacheTransfer">
66 <property name="redisTemplate" ref="redisTemplate"/>
67 </bean>
68</beans>
69
70
桥接的工具类
RedisCache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119 1package com.li.util;
2
3
4import org.apache.ibatis.cache.Cache;
5import org.slf4j.Logger;
6import org.slf4j.LoggerFactory;
7import org.springframework.dao.DataAccessException;
8import org.springframework.data.redis.connection.RedisConnection;
9import org.springframework.data.redis.core.RedisCallback;
10import org.springframework.data.redis.core.RedisTemplate;
11
12import java.util.concurrent.TimeUnit;
13import java.util.concurrent.locks.ReadWriteLock;
14import java.util.concurrent.locks.ReentrantReadWriteLock;
15
16
17public class RedisCache implements Cache //实现类
18{
19 private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
20
21 private static RedisTemplate<String,Object> redisTemplate;
22
23 private final String id;
24
25 /**
26 * The {@code ReadWriteLock}.
27 */
28 private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
29
30 @Override
31 public ReadWriteLock getReadWriteLock()
32 {
33 return this.readWriteLock;
34 }
35
36 public static void setRedisTemplate(RedisTemplate redisTemplate) {//给RedisTemplate赋值
37 RedisCache.redisTemplate = redisTemplate;
38 }
39
40 public RedisCache(final String id) {
41 if (id == null) {
42 throw new IllegalArgumentException("Cache instances require an ID");
43 }
44 logger.debug("MybatisRedisCache:id=" + id);
45 this.id = id;
46 }
47
48 @Override
49 public String getId() {
50 return this.id;
51 }
52
53 @Override
54 public void putObject(Object key, Object value) {
55 try{
56 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value);
57 if(null!=value)
58 redisTemplate.opsForValue().set(key.toString(),value,60, TimeUnit.SECONDS);//设置存放时间
59 }catch (Exception e){
60 e.printStackTrace();
61 logger.error("redis保存数据异常!");
62 }
63 }
64
65 @Override
66 public Object getObject(Object key) {
67 try{
68 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key="+key);
69 if(null!=key)
70 return redisTemplate.opsForValue().get(key.toString());
71 }catch (Exception e){
72 e.printStackTrace();
73 logger.error("redis获取数据异常!");
74 }
75 return null;
76 }
77
78 @Override
79 public Object removeObject(Object key) {
80 try{
81 if(null!=key)
82 return redisTemplate.expire(key.toString(),1,TimeUnit.DAYS);
83 }catch (Exception e){
84 e.printStackTrace();
85 logger.error("redis获取数据异常!");
86 }
87 return null;
88 }
89
90 @Override
91 public void clear() {
92 Long size=redisTemplate.execute(new RedisCallback<Long>() {
93 @Override
94 public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
95 Long size = redisConnection.dbSize();
96 //连接清除数据
97 redisConnection.flushDb();
98 redisConnection.flushAll();
99 return size;
100 }
101 });
102 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "个对象");
103 }
104
105 @Override
106 public int getSize() {
107 Long size = redisTemplate.execute(new RedisCallback<Long>() {
108 @Override
109 public Long doInRedis(RedisConnection connection)
110 throws DataAccessException {
111 return connection.dbSize();
112 }
113 });
114 return size.intValue();
115 }
116}
117
118
119
RedisCacheTransfer
负责把RedisCache注入到工具类中去
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1package com.li.util;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.data.redis.core.RedisTemplate;
5
6public class RedisCacheTransfer {
7// 整合完后通过RedisTemplate操作数据 这里将RedisTemplate注入
8 @Autowired
9 public void setRedisTemplate(RedisTemplate redisTemplate) {
10 RedisCache.setRedisTemplate(redisTemplate);
11 }
12}
13
14
15
然后在XXXMapper.xml中添加开启缓存的配置,
这配置的就是刚刚的桥接工具类,而ehcache配置的是jar包自带的桥接类
1
2
3
4 1<!-- 将缓存方式替换为redis-->
2 <cache type="com.li.util.RedisCache"></cache>
3
4
把实体类实现序列化,implements Serializable
用JUnit测试
使用的方法跟之前一样只不过用的缓存不同,这次它调用的是redis的缓存
还可以在redis里面看见刚刚查询的数据,工具类中设定了存储时间位一分钟,也就是一分钟后数据就自动删除了