1、首先你的有個SSM工程html
2、添加引用java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SSMRedisDemo</groupId>
<artifactId>SSMRedisDemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SSMRedisDemo Maven Webapp</name>
<url>http://maven.apache.org</url>mysql
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.0.RELEASE</spring.version>
</properties>web
<dependencies>redis
<!-- spring mvc related.....start --> <!-- TODO: replace jackson with fastjson -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
<!-- spring mvc related.....end -->spring
<!-- mybatis orm related.....start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!-- mybatis orm related.....end -->sql
<!-- project log related.....start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- project log related.....end -->數據庫
<!-- redis cache related.....start -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<!-- redis cache related.....end -->apache
</dependencies>json
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
3、系統參數配置
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
4、applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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 annotation related... start -->
<context:component-scan base-package="com.ssm.serviceImpl" />
<context:component-scan base-package="com.ssm.utils" />
<!-- class annotation related... end -->
<!-- mybatis related... start -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource "
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useUnicode=true&characterEncoding=utf8" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="acquireIncrement" value="1" />
<property name="initialPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="5" />
<property name="maxStatements" value="100" />
<property name="testConnectionOnCheckout" value="true" />
</bean>
<!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml文件 <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property> -->
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao" />
</bean>
<!-- mybatis related... end -->
<!-- transaction config related... start -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- transaction config related... end -->
<!-- redis config start -->
<!-- 配置JedisPoolConfig實例 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 配置JedisConnectionFactory -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value="${redis.pass}" /> -->
<property name="database" value="${redis.dbIndex}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- 配置RedisCacheManager -->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg name="redisOperations" ref="redisTemplate" />
<property name="defaultExpiration" value="${redis.expiration}" />
</bean>
<!-- 配置RedisCacheConfig -->
<bean id="redisCacheConfig" class="com.ssm.utils.RedisCacheConfig">
<constructor-arg ref="jedisConnectionFactory" />
<constructor-arg ref="redisTemplate" />
<constructor-arg ref="redisCacheManager" />
</bean>
<!-- redis config end -->
</beans>
5、springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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 annotation related... start
<context:component-scan base-package="com.ssm.controller" />
class annotation related... end
-->
<!-- 添加註解驅動 使用註解標註的類生效-->
<mvc:annotation-driven />
<!-- 設置能訪問靜態資源 -->
<mvc:default-servlet-handler/>
<!--掃描controller-->
<context:component-scan base-package="com.ssm.controller" />
<!-- jsp page related... start -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- jsp page related... end -->
<!-- rest json related... start -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<!-- rest json related... end -->
</beans>
6、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
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">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- 加載spring bean -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 編碼過濾器 -->
<filter>
<filter-name>springfilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
7、UserController
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;
}
}
8、實體序列化
9、服務實現層添加緩存
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緩存中讀取數據,這樣就減小了跟數據庫之間的交互。而後修改、刪除、增長操做就會清除緩存,保持數據的一致性。
10、RedisCacheConfig: 須要增長這個配置類,會在applicationContex配置文件中註冊這個bean。
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<String, String> redisTemplate;
private volatile RedisCacheManager redisCacheManager;
public RedisCacheConfig() {
super();
}
/**
* 帶參數的構造方法 初始化全部的成員變量
*
* @param jedisConnectionFactory
* @param redisTemplate
* @param redisCacheManager
*/
public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate<String, String> redisTemplate,
RedisCacheManager redisCacheManager) {
this.jedisConnectionFactory = jedisConnectionFactory;
this.redisTemplate = redisTemplate;
this.redisCacheManager = redisCacheManager;
}
public JedisConnectionFactory getJedisConnecionFactory() {
return jedisConnectionFactory;
}
public RedisTemplate<String, String> 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();
}
};
}
}
11、接口測試
一、表數據
二、
查詢 :
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}
三、修改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}
四、清除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