ssm整合redis和mysql_ssm整合redis - 开源中国首席碉堡了的个人空间 - OSCHINA - 中文开源技术交流社区...

本文档详细介绍了如何在SSM(Spring、SpringMVC、MyBatis)项目中集成Redis作为缓存,通过配置XML、属性文件以及使用Spring的缓存注解来实现数据查询的缓存优化。同时,提供了接口测试案例,展示了缓存的添加、修改和清除操作,以及在数据变更后如何保持缓存一致性。
摘要由CSDN通过智能技术生成

一、首先你的有个SSM工程

b7acefe16a08d9fc4529267029a00c28.png

二、添加引用

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

三、系统参数配置

a1373a1daedffdba7563a8eca62e2d87.png

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

99e1fac7adcf7825c11dda9c3a588695.png

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;

}

}

八、实体序列化

0bca8b3d18ded6c744495c7aece95df7.png

九、服务实现层添加缓存

6b8f03c8d192b4b70c6c633aac7eed7e.png

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。

c1727ba80040bbab91c52d9b6693767f.png

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、表数据

96bf48f04c8255d48972028dabd473db.png

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}

参考:https://www.cnblogs.com/hello-daocaoren/p/7891907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值