SSM项目架构搭建
该图是一个搭建好了的SSM项目结构,用maven管理项目依赖。
一,添加项目依赖(我直接贴pom.xml文件了)
1
2
3
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 4.0.0
6
7 indi.lwc
8 Spring_Redis_Demo
9 1.0-SNAPSHOT
10 war
11
12 Spring_Redis_Demo Maven Webapp
13
14 http://www.example.com
15
16
17 4.3.7.RELEASE
18 UTF-8
19 1.7
20 1.7
21
22
23
24
25
26
27 junit
28 junit
29 4.12
30 test
31
32
33
34
35 mysql
36 mysql-connector-java
37 5.1.37
38 runtime
39
40
41
42
43 org.mybatis
44 mybatis
45 3.4.2
46
47
48 org.mybatis
49 mybatis-spring
50 1.3.1
51
52
53
54
55 taglibs
56 standard
57 1.1.2
58
59
60 jstl
61 jstl
62 1.2
63
64
65 com.fasterxml.jackson.core
66 jackson-databind
67 2.8.7
68
69
70 javax.servlet
71 javax.servlet-api
72 3.1.0
73
74
75
76
77
78 org.springframework
79 spring-core
80 ${spring.version}
81
82
83 org.springframework
84 spring-beans
85 ${spring.version}
86
87
88 org.springframework
89 spring-context
90 ${spring.version}
91
92
93
94 org.springframework
95 spring-jdbc
96 ${spring.version}
97
98
99 org.springframework
100 spring-tx
101 ${spring.version}
102
103
104
105 org.springframework
106 spring-web
107 ${spring.version}
108
109
110 org.springframework
111 spring-webmvc
112 ${spring.version}
113
114
115
116 org.springframework
117 spring-test
118 ${spring.version}
119
120
121
122
123 commons-collections
124 commons-collections
125 3.2
126
127
128 net.coobird
129 thumbnailator
130 0.4.8
131
132
133 com.github.penggle
134 kaptcha
135 2.3.2
136
137
138 commons-fileupload
139 commons-fileupload
140 1.3.2
141
142
143 net.sf.json-lib
144 json-lib
145 2.4
146 jdk15
147
148
149 commons-collections
150 commons-collections
151
152
153 commons-lang
154 commons-lang
155
156
157 commons-logging
158 commons-logging
159
160
161
162
163 com.thoughtworks.xstream
164 xstream
165 1.4.9
166
167
168 org.apache.taglibs
169 taglibs-standard-spec
170 1.2.1
171
172
173 org.apache.taglibs
174 taglibs-standard-impl
175 1.2.1
176
177
178 org.dom4j
179 dom4j
180 2.0.0
181
182
183
184
185 c3p0
186 c3p0
187 0.9.1.2
188
189
190
191
192 redis.clients
193 jedis
194 2.9.0
195
196
197 org.springframework.data
198 spring-data-redis
199 1.6.2.RELEASE
200
201
202
203 org.mybatis
204 mybatis-ehcache
205 1.0.0
206
207
208
209
210
211
212 Spring_Redis_Demo
213
214
215
216
217 maven-clean-plugin
218 3.1.0
219
220
221
222 maven-resources-plugin
223 3.0.2
224
225
226
227 maven-compiler-plugin
228 3.8.0
229
230 1.7
231 1.7
232 UTF-8
233
234
235
236
237 maven-surefire-plugin
238 2.22.1
239
240
241
242 maven-war-plugin
243 3.2.2
244
245
246
247 maven-install-plugin
248 2.5.2
249
250
251
252 maven-deploy-plugin
253 2.8.2
254
255
256
257
258
259
二,相关配置文件(对照上面的项目结构图,放在对应的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
2
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/beans6 http://www.springframework.org/schema/beans/spring-beans.xsd7 http://www.springframework.org/schema/context8 http://www.springframework.org/schema/context/spring-context.xsd9 http://www.springframework.org/schema/mvc10 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
11
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
39
40
41
43
44
45 text/html;charset=UTF-8
46
47
48
49
50
51
52
53
54
55
4.spring-dao.xml (持久层dao层配置文件,mybatis)
1
2
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/beans7 http://www.springframework.org/schema/beans/spring-beans.xsd8 http://www.springframework.org/schema/context9 http://www.springframework.org/schema/context/spring-context.xsd10 http://www.springframework.org/schema/tx11 http://www.springframework.org/schema/tx/spring-tx.xsd">
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
5.spring-service.xml (服务层配置文件,处理逻辑,减少耦合层)。
1
2
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/beans7 http://www.springframework.org/schema/beans/spring-beans.xsd8 http://www.springframework.org/schema/context9 http://www.springframework.org/schema/context/spring-context.xsd10 http://www.springframework.org/schema/tx11 http://www.springframework.org/schema/tx/spring-tx.xsd">
12
13
14
15
16
17
18 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
19
20
21
22
23
24
25
26
27
6.spring-redis.xml (配置redis相关类,如RedisTemplate,JedisPoolConfig等)
1
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/beans4 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd5 http://www.springframework.org/schema/context6 http://www.springframework.org/schema/context/spring-context-3.2.xsd">
7 redis相关类 spring托管
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
7.mybatis.xml (mybatis全局配置文件)
1
2 "http://mybatis.org/dtd/mybatis-3-config.dtd">
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
8.web.xml配置 (通常会自动生成,在webapp/web-inf下面)
1
2
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
8
9 seckill-dispatcher
10 org.springframework.web.servlet.DispatcherServlet
11
13
14 contextConfigLocation
15 classpath:spring/spring-*.xml
16
17
18
19
20 seckill-dispatcher
21
22 /
23
24
25
26
三,需要的相关类文件(对照最上面的项目结构图,放在对应的包内)
1.RedisConfig.java (redis对象序列化类,你要存对象就必须配置。因为redis支持的数据类型只有 String,hash,List,Set,zset) 放在cache包下面。
1 packageindi.lwc.redis.cache;2
3 importcom.fasterxml.jackson.annotation.JsonAutoDetect;4 importcom.fasterxml.jackson.annotation.PropertyAccessor;5 importcom.fasterxml.jackson.databind.ObjectMapper;6 importorg.springframework.context.annotation.Bean;7 importorg.springframework.context.annotation.Configuration;8 importorg.springframework.data.redis.connection.RedisConnectionFactory;9 importorg.springframework.data.redis.core.RedisTemplate;10 importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;11 importorg.springframework.data.redis.serializer.StringRedisSerializer;12
13 /**
14 * 如果我们想使用RedisTemplate存取对象,15 * 那我们只要设置对应的序列器就行了16 */
17 @Configuration18 public classRedisConfg {19
20 privateRedisConnectionFactory redisConnectionFactory;21
22
23 publicRedisConfg(RedisConnectionFactory redisConnectionFactory){24 this.redisConnectionFactory=redisConnectionFactory;25 }26 /**
27 * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类28 *29 *@return
30 */
31 @Bean32 public RedisTemplateredisTemplate() {33 RedisTemplate redisTemplate = new RedisTemplate<>();34 redisTemplate.setConnectionFactory(redisConnectionFactory);35
36 //使用Jackson2JsonRedisSerialize 替换默认序列化
37 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);38
39 ObjectMapper objectMapper = newObjectMapper();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(newStringRedisSerializer());47 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);48 redisTemplate.setHashKeySerializer(newStringRedisSerializer());49 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);50 redisTemplate.afterPropertiesSet();51 returnredisTemplate;52 }53
54 }
2,Emp.java (实体类) 放在bean包下。
1 packageindi.lwc.redis.bean;2
3 importjava.io.Serializable;4 importjava.util.Date;5
6 public class Emp implementsSerializable {7 privateInteger eno;8 privateString ename;9 privateString esex;10 private floatsal;11 privateInteger dno;12 privateDate join_date;13 privateInteger elevel;14 privateString password;15
16
17 publicInteger getEno() {18 returneno;19 }20
21 public voidsetEno(Integer eno) {22 this.eno =eno;23 }24
25 publicString getEname() {26 returnename;27 }28
29 public voidsetEname(String ename) {30 this.ename =ename;31 }32
33 publicString getEsex() {34 returnesex;35 }36
37 public voidsetEsex(String esex) {38 this.esex =esex;39 }40
41 public floatgetSal() {42 returnsal;43 }44
45 public void setSal(floatsal) {46 this.sal =sal;47 }48
49 publicInteger getDno() {50 returndno;51 }52
53 public voidsetDno(Integer dno) {54 this.dno =dno;55 }56
57 publicDate getJoin_date() {58 returnjoin_date;59 }60
61 public voidsetJoin_date(Date join_date) {62 this.join_date =join_date;63 }64
65 publicInteger getElevel() {66 returnelevel;67 }68
69 public voidsetElevel(Integer elevel) {70 this.elevel =elevel;71 }72
73 publicString getPassword() {74 returnpassword;75 }76
77 public voidsetPassword(String password) {78 this.password =password;79 }80
81 @Override82 publicString 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 packageindi.lwc.redis.dao;2
3 importindi.lwc.redis.bean.Emp;4
5 public interfaceEmpDao {6
7
8 /**
9 * 根据id查询用户10 *@return
11 */
12 Emp queryEmpById(Integer eId);13
14 /**
15 * 更新员工16 *@paramemp17 *@return
18 */
19 intupdateEmp(Emp emp);20
21 /**
22 *删除指定id23 *@parameId24 *@return
25 */
26 intdeleteEmp(Integer eId);27
28 /**
29 * 添加员工30 *@paramemp31 *@return
32 */
33 intinsertEmp(Emp emp);34 }
4.EmpDao.xml 放在mapper包下
1
2 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5
6
7 select * from emp where eno=#{eId}8
9
10 update emp11
12
13 ename=#{ename},14
15
16 esex=#{esex},17
18
19 sal=#{sal},20
21
22 dno=#{dno},23
24
25 join_date=#{join_date},26
27
28 elevel=#{elevel},29
30
31 password=#{password}32
33
34 where eno=#{eno}35
36
37 delete from emp where eno=#{eId}38
39
40
41 select last_insert_id()42
43 insert into emp(ename,esex,sal,dno,join_date,elevel,password) VALUE44 (#{ename},#{esex},#{sal},#{dno},#{join_date},#{elevel},#{password})45
46
5.EmpService.Interface 放在sercie包下
1 packageindi.lwc.redis.service;2
3 importindi.lwc.redis.bean.Emp;4
5 public interfaceEmpService {6
7
8 /**
9 * 根据id查询emp10 *@parameId11 *@return
12 */
13 Emp findEmpById(inteId);14
15
16 /**
17 * 更新员工信息18 *@paramemp19 *@return
20 */
21 Emp replaceEmp(Emp emp);22
23 /**
24 * 删除员工信息25 *@parameId26 *@return
27 */
28 int removeEmp(inteId);29
30 /**
31 * 添加员工32 *@paramemp33 *@return
34 */
35 Emp addEmp(Emp emp);36 }
6.EmpServiceImpl.java (逻辑处理类,redis的存取操作也在这个类)
1 packageindi.lwc.redis.service.impl;2
3 importindi.lwc.redis.bean.Emp;4 importindi.lwc.redis.dao.EmpDao;5 importindi.lwc.redis.service.EmpService;6 importindi.lwc.redis.util.RedisTemplateUtil;7 importorg.springframework.beans.factory.annotation.Autowired;8 importorg.springframework.cglib.beans.BeanMap;9 importorg.springframework.data.redis.core.HashOperations;10 importorg.springframework.data.redis.core.RedisTemplate;11 importorg.springframework.data.redis.core.ValueOperations;12 importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;13 importorg.springframework.stereotype.Service;14
15
16 importjavax.annotation.Resource;17 importjava.io.ByteArrayOutputStream;18 importjava.io.IOException;19 importjava.io.ObjectOutputStream;20 importjava.util.HashMap;21 importjava.util.List;22 importjava.util.Map;23
24 @Service25 public class EmpServiceImpl implementsEmpService {26
27 @Resource28 privateEmpDao empDao;29
30 @Autowired31 privateRedisTemplate redisTemplate;32
33 @Override34 public Emp findEmpById(inteId) {35 ValueOperations valueOperations =redisTemplate.opsForValue();36 RedisTemplateUtil redisTemplateUtil =newRedisTemplateUtil(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 returnemp;53 }54
55 @Override56 publicEmp replaceEmp(Emp emp) {57 empDao.updateEmp(emp);58 returnemp;59 }60
61 @Override62 public int removeEmp(inteId) {63 returnempDao.deleteEmp(eId);64 }65
66 @Override67 publicEmp addEmp(Emp emp) {68 empDao.insertEmp(emp);69 returnemp;70 }71
72 /**
73 * 将对象属性转化为map结合74 */
75 public static MapbeanToMap(T bean) {76 Map 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 returnmap;84 }85
86
87 /**
88 * 将map集合中的数据转化为指定对象的同名属性中89 */
90 public static T mapToBean(Map map,Class clazz) throwsException {91 T bean =clazz.newInstance();92 BeanMap beanMap =BeanMap.create(bean);93 beanMap.putAll(map);94 returnbean;95 }96
97
98 }
7.RedisTemplateUtil.java (RedisTemplate各大成员内的api方法较多,所以我们通常将String,list,hash,set,zset 等数据类型的基本方法封装起来)
1 packageindi.lwc.redis.util;2
3 importorg.springframework.data.redis.core.RedisTemplate;4 importorg.springframework.data.redis.core.ValueOperations;5
6 importjava.util.List;7 importjava.util.Map;8 importjava.util.Set;9
10 public classRedisTemplateUtil {11
12 privateRedisTemplate redisTemplate;13
14 publicRedisTemplateUtil(RedisTemplate redisTemplate){15 this.redisTemplate =redisTemplate;16 }17
18 //将多种类型的值存入缓存
19 public voidset(String key, Object value){20 ValueOperations valueOperations =redisTemplate.opsForValue();21 valueOperations.set(key,value);22 }23
24 //获取指定的key值
25 publicObject get(String key){26 returnredisTemplate.opsForValue().get(key);27 }28
29 //将list存入缓存
30 public voidsetList(String key, List value){31 redisTemplate.opsForList().leftPush(key,value);32 }33
34 //获取指定key的list值
35 publicObject getList(String key){36 returnredisTemplate.opsForList().leftPop(key);37 }38
39 //将set存入缓存
40 public voidsetSet(String key, Set value){41 redisTemplate.opsForSet().add(key,value);42 }43
44 //获取set
45 publicObject getSet(String key){46 returnredisTemplate.opsForSet().members(key);47 }48
49 //将map存入缓存
50 public voidsetHash(String key , Map value){51 redisTemplate.opsForHash().putAll(key,value);52 }53
54 //获取map
55 publicObject getHash(String key){56 returnredisTemplate.opsForHash().entries(key);57 }58
59 //删除某个key
60 public voiddelete(String key){61 redisTemplate.delete(key);62 }63
64 }
8.BaseTest.java (启动配置)
1 packageindi.lwc.test;2
3 importorg.junit.runner.RunWith;4 importorg.springframework.test.context.ContextConfiguration;5 importorg.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 classBaseTest {13
14
15 }
9.RedisTest.java (测试类)
1 packageindi.lwc.test;2
3 importindi.lwc.redis.bean.Emp;4 importindi.lwc.redis.service.EmpService;5 importorg.junit.Assert;6 importorg.junit.Test;7
8 importjavax.annotation.Resource;9
10 public class RedisTest extendsBaseTest {11
12 @Resource13 privateEmpService empService;14
15
16 @Test17 public voidtestFindEmpById(){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
用来标注在需要清除缓存元素的方法或类上的。