一、首先你的有个SSM工程

ssm 配置redis ssm框架整合redis_ssm整合redis和mysql

二、添加引用

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
SSMRedisDemo
SSMRedisDemo
war
0.0.1-SNAPSHOT
SSMRedisDemo Maven Webapp
http://maven.apache.org
UTF-8
4.2.0.RELEASE
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-web
${spring.version}
javax.servlet
jstl
1.2
commons-logging
commons-logging
1.1.3
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.fasterxml.jackson.core
jackson-annotations
2.6.1
com.fasterxml.jackson.core
jackson-core
2.6.1
com.fasterxml.jackson.core
jackson-databind
2.6.1
org.springframework
spring-orm
${spring.version}
org.mybatis
mybatis-spring
1.2.3
mysql
mysql-connector-java
5.1.36
org.mybatis
mybatis
3.3.0
c3p0
c3p0
0.9.1.2
org.slf4j
slf4j-log4j12
1.7.12
log4j
log4j
1.2.17
org.springframework.data
spring-data-redis
1.6.0.RELEASE
redis.clients
jedis
2.7.3
maven-compiler-plugin
3.1
1.7
1.7
maven-war-plugin
2.4
WebContent
false

三、系统参数配置

ssm 配置redis ssm框架整合redis_redis_02

jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/user
username=root
password=root
initialSize=10
maxActive=300
maxIdle=20
minIdle=1
maxWait=60000
log4j.properties
log4j.rootLogger=DEBUG,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
redis.properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
#redis.pass=password
redis.dbIndex=0
redis.expiration=3000
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
四、applicationContext.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
classpath:jdbc.properties
classpath:redis.properties
destroy-method="close">
value="jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useUnicode=true&characterEncoding=utf8" />
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
五、springmvc.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
value="org.springframework.web.servlet.view.JstlView" />
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
application/json;charset=UTF-8
六、web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
Archetype Created Web Application
/index.jsp
contextConfigLocation
classpath:spring/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
springfilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
springfilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/springmvc.xml
1
true
SpringMVC
/

七、UserController

ssm 配置redis ssm框架整合redis_ssm 配置redis_03

package com.it.demo.controller;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.it.demo.bean.UserBaseInfo;
import com.it.demo.service.IUserService;
@Controller
@RequestMapping("/test")
public class TestController {
private static Logger logger = Logger.getLogger(TestController.class);
@Resource
private IUserService userService;
// 注册请求
@RequestMapping("/demo")
@ResponseBody
private Object demo(Long id) {
UserBaseInfo user = userService.queryUserInfo(id);
user.setuNick("我是谁");
return user;
}
// 添加缓存
@RequestMapping("/demo4")
@ResponseBody
private Object demo4(Long id) {
UserBaseInfo user = userService.queryUserInfo(id);
return user;
}
// 删除缓存
@RequestMapping("/demo5")
@ResponseBody
private Object demo5(Long id) {
UserBaseInfo user = userService.queryUserById(id);
return user;
}
}

八、实体序列化

ssm 配置redis ssm框架整合redis_spring_04

九、服务实现层添加缓存

ssm 配置redis ssm框架整合redis_spring_05

package com.it.demo.service.impl;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.it.demo.bean.UserBaseInfo;
import com.it.demo.dao.UserBaseInfoMapper;
import com.it.demo.service.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private UserBaseInfoMapper userBaseInfoMapper;
private static Logger logger = Logger.getLogger(UserServiceImpl.class);
@Cacheable("queryUserInfo")
public UserBaseInfo queryUserInfo(Long id) {
return userBaseInfoMapper.selectByPrimaryKey(id);
}
@CacheEvict(value= {"queryUserInfo"},allEntries=true)
public UserBaseInfo queryUserById(Long id) {
return userBaseInfoMapper.selectByPrimaryKey(id);
}
}

小注:

缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放到了redis中去,

* 然后第二次发起该条查询时就可以从redis中去读取查询的结果,从而不与MySQL交互,从而达到优化的效果,

* redis的查询速度之于MySQL的查询速度相当于 内存读写速度 /硬盘读写速度

* @Cacheable("a")注解的意义就是把该方法的查询结果放到redis中去,下一次再发起查询就去redis中去取,存在redis中的数据的key就是a;

* @CacheEvict(value={"a","b"},allEntries=true) 的意思就是执行该方法后要清除redis中key名称为a,b的数据;

缓存主要在service层进行,查询的结果会缓存,把对象序列号存到redis中去,key就是注解中的参数,例如@Cacheable("findUsers"): 存在redis中的key就是findUsers。缓存了这个结果之后再次请求这个方法就不会去数据库中查,而是从redis缓存中读取数据,这样就减少了跟数据库之间的交互。然后修改、删除、增加操作就会清除缓存,保持数据的一致性。

十、RedisCacheConfig: 需要增加这个配置类,会在applicationContex配置文件中注册这个bean。

ssm 配置redis ssm框架整合redis_spring_06

package com.it.demo.springmvc;
import java.lang.reflect.Method;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
* 通过spring管理redis缓存配置
*
* @author Administrator
*
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
private volatile JedisConnectionFactory jedisConnectionFactory;
private volatile RedisTemplate redisTemplate;
private volatile RedisCacheManager redisCacheManager;
public RedisCacheConfig() {
super();
}
/**
* 带参数的构造方法 初始化所有的成员变量
*
* @param jedisConnectionFactory
* @param redisTemplate
* @param redisCacheManager
*/
public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate redisTemplate,
RedisCacheManager redisCacheManager) {
this.jedisConnectionFactory = jedisConnectionFactory;
this.redisTemplate = redisTemplate;
this.redisCacheManager = redisCacheManager;
}
public JedisConnectionFactory getJedisConnecionFactory() {
return jedisConnectionFactory;
}
public RedisTemplate getRedisTemplate() {
return redisTemplate;
}
public RedisCacheManager getRedisCacheManager() {
return redisCacheManager;
}
@Bean
public KeyGenerator customKeyGenerator() {
return new KeyGenerator() {
public Object generate(Object target, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}

十一、接口测试

1、表数据

ssm 配置redis ssm框架整合redis_ssm 配置redis_07

2、

查询 :

http://127.0.0.1:8080/demo-webapp/test/demo4?id=10

输出:

{"uId":10,"uNick":"Nick555","uName":"Name333","uPhone":"18810910555","uTel":null,"uIdType":1,"uIdCode":"uCode17555","uAddr":"安徽省凤阳县小岗村555户","uSex":1,"uSign":null,"uSchool":"阜阳市红旗中学","uAge":19,"uBirth":975340800000}

3、修改u_name的值为Name555

查询:

http://127.0.0.1:8080/demo-webapp/test/demo4?id=10

输出:

{"uId":10,"uNick":"Nick555","uName":"Name333","uPhone":"18810910555","uTel":null,"uIdType":1,"uIdCode":"uCode17555","uAddr":"安徽省凤阳县小岗村555户","uSex":1,"uSign":null,"uSchool":"阜阳市红旗中学","uAge":19,"uBirth":975340800000}

4、清除Redis缓存再查询

查询:

http://127.0.0.1:8080/demo-webapp/test/demo5?id=10

http://127.0.0.1:8080/demo-webapp/test/demo4?id=10

输出:

{"uId":10,"uNick":"Nick555","uName":"Name555","uPhone":"18810910555","uTel":null,"uIdType":1,"uIdCode":"uCode17555","uAddr":"安徽省凤阳县小岗村555户","uSex":1,"uSign":null,"uSchool":"阜阳市红旗中学","uAge":19,"uBirth":975340800000}