SSM之整合Redis

Redis安装与使用
第一步当然是安装Redis,这里以Windows上的安装为例。
- 首先下载Redis,可以选择msi或zip包安装方式
- zip方式需打开cmd窗口,在解压后的目录下运行
redis-server redis.windows.conf启动Redis - 采用msi方式安装后Redis默认启动,不需要进行任何配置
- 可以在redis.windows.conf文件中修改Redis端口号、密码等配置,修改完成后使用
redis-server redis.windows.conf命令重新启动 - 在Redis安装目录下执行
redis-cli -h 127.0.0.1 -p 6379 -a 密码打开Redis操作界面 - 如果报错
(error) ERR operation not permitted,使用auth 密码进行验证
SSM整合Redis
这里直接在上一篇SSM之框架整合的基础上进行Redis整合,这里需要注意,存入Redis的pojo类必须实现Serializable接口。
配置pom.xml引入Redis依赖
<!--redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=redis
redis.maxIdle=100
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
defaultCacheExpireTime=3600
applicationContext-redis.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:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--引入Redis配置文件-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<!-- jedis 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWait}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<!-- redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"/>
<property name="port" value="${redis.port}"/>
<property name="hostName" value="${redis.host}"/>
<property name="password" value="${redis.password}"/>
<property name="timeout" value="${redis.timeout}"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
<!-- 缓存拦截器配置 -->
<bean id="methodCacheInterceptor" class="com.zkh.interceptor.MethodCacheInterceptor">
<property name="redisUtil" ref="redisUtil"/>
<property name="defaultCacheExpireTime" value="${defaultCacheExpireTime}"/>
<!-- 禁用缓存的类名列表 -->
<property name="targetNamesList">
<list>
<value></value>
</list>
</property>
<!-- 禁用缓存的方法名列表 -->
<property name="methodNamesList">
<list>
<value></value>
</list>
</property>
</bean>
<bean id="redisUtil" class="com.zkh.util.RedisUtil">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
<!--配置切面拦截方法 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="controllerMethodPointcut" expression="
execution(* com.zkh.service.impl.*.select*(..))"/>
<aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/>
</aop:config>
</beans>
MethodCacheInterceptor.java
package com.zkh.interceptor;
import com.zkh.util.RedisUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import java.util.List;
/**
* Redis缓存过滤器
*/
public class MethodCacheInterceptor implements MethodInterceptor {
private RedisUtil redisUtil;
private List<String> targetNamesList; // 禁用缓存的类名列表
private List<String> methodNamesList; // 禁用缓存的方法列表
private String defaultCacheExpireTime; // 缓存默认的过期时间
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object value = null;
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
if (!isAddCache(targetName, methodName)) {
// 跳过缓存返回结果
return invocation.proceed();
}
Object[] arguments = invocation.getArguments();
String key = getCacheKey(targetName, methodName, arguments);
try {
// 判断是否有缓存
if (redisUtil.exists(key)) {
return redisUtil.get(key);
}
// 写入缓存
value = invocation.proceed();
if (value != null) {
final String tkey = key;
final Object tvalue = value;
new Thread(new Runnable() {
@Override
public void run() {
redisUtil.set(tkey, tvalue, Long.parseLong(defaultCacheExpireTime));
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
if (value == null) {
return invocation.proceed();
}
}
return value;
}
/**
* 是否加入缓存
*
* @return
*/
private boolean isAddCache(String targetName, String methodName) {
boolean flag = true;
if (targetNamesList.contains(targetName)
|| methodNamesList.contains(methodName) || targetName.contains("$$EnhancerBySpringCGLIB$$")) {
flag = false;
}
return flag;
}
/**
* 创建缓存key
*
* @param targetName
* @param methodName
* @param arguments
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) {
StringBuffer sbu = new StringBuffer();
sbu.append(targetName).append("_").append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sbu.append("_").append(arguments[i]);
}
}
return sbu.toString();
}
public void setRedisUtil(RedisUtil redisUtil) {
this.redisUtil = redisUtil;
}
public void setTargetNamesList(List<String> targetNamesList) {
this.targetNamesList = targetNamesList;
}
public void setMethodNamesList(List<String> methodNamesList) {
this.methodNamesList = methodNamesList;
}
public void setDefaultCacheExpireTime(String defaultCacheExpireTime) {
this.defaultCacheExpireTime = defaultCacheExpireTime;
}
}
RedisUtil.java 工具类
package com.zkh.util;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类
*/
public class RedisUtil {
private RedisTemplate<Serializable, Object> redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate
.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate
.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate
.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void setRedisTemplate(
RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
效果展示

刚开始Redis中没有任何记录,接下来访问一下第一页记录

再查看缓存,记录已经存如Redis,并且第一次访问会从Mysql中读取数据


按F5刷新页面,从Tomcat控制台可以看到没有进行SQL查询,而是直接从Redis中读取缓存数据,减轻了数据库的负担


具体代码已发布在Github上,地址:SSM
本文为作者kMacro原创,转载请注明来源:http://www.jianshu.com/p/7fecfad2970c。
SSM之整合Redis的更多相关文章
- 完整SpringBoot Cache整合redis缓存(二)
缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...
- 05.haproxy+mysql负载均衡 整合 redis集群+ssm
本篇重点讲解haproxy+mysql负载均衡,搭建完成后与之前搭建的redis+ssm进行整合 (注:这里用到了两台mysql数据库,分别安装两台虚拟机上,已经成功实现主主复制,如果有需要,请查看我 ...
- ssm 整合 redis(简单教程)
最后我建议大家使用 Spring StringRedisTemplate 配置,参阅: http://blog.csdn.net/hanjun0612/article/details/78131333 ...
- SSM+redis整合(mybatis整合redis做二级缓存)
SSM:是Spring+Struts+Mybatis ,另外还使用了PageHelper 前言: 这里主要是利用redis去做mybatis的二级缓存,mybaits映射文件中所有的select都会刷 ...
- 网站性能优化小结和spring整合redis
现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...
- 使用IntelliJ IDEA创建Maven聚合工程、创建resources文件夹、ssm框架整合、项目运行一体化
一.创建一个空的项目作为存放整个项目的路径 1.选择 File——>new——>Project ——>Empty Project 2.WorkspaceforTest为项目存放文件夹 ...
- JAVAEE——宜立方商城01:电商行业的背景、商城系统架构、后台工程搭建、SSM框架整合
1. 学习计划 第一天: 1.电商行业的背景. 2.宜立方商城的系统架构 a) 功能介绍 b) 架构讲解 3.工程搭建-后台工程 a) 使用maven搭建工程 b) 使用maven的tomcat插件启 ...
- Spring+SpringMVC+Mybatis整合redis
SSM整合redis redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列. 这里用的是ssm框架+maven构建的项目 ...
- SSM框架集成Redis
SSM-Spring+SpringMVC+Mybatis框架相信大家都很熟悉了,但是有的时候需要频繁访问数据库中不变或者不经常改变的数据,就会加重数据库的负担,这时我们就会想起Redis Redis是 ...
随机推荐
- vue.js基础知识篇(1):简介、数据绑定
目录第一章:vue.js是什么? 第二章:数据绑定第三章:指令第四章:计算属性第五章:表单控件绑定代码链接: http://pan.baidu.com/s/1qXCfzRI 密码: 5j79 第一章: ...
- Windows下mysql忘记root密码
1. 首先检查mysql服务是否启动,若已启动则先将其停止服务,可在开始菜单的运行,使用命令: net stop mysql 打开第一个cmd窗口,切换到mysql的bin目录,运行命令: mysql ...
- django框架简介
-------------------MVC与MVT框架-------------------1.MVC MVC框架的核心思想是:解耦.降低各功能模块之间的耦合性,方便将来变化时,更容易重构代码,最大 ...
- C++内存布局详解
一个由C/C++编译的程序除了存放函数二进制代码的程序代码段(code段)外,数据占用的内存大致分为以下几个部分: 1.栈区(stack) 存放局部变量.函数参数.返回数据.返回地址等.系统自动分配释 ...
- chrome开发工具指南(四)
Sources 面板中 代码段是您可以从任何页面运行的小脚本(类似于小书签). 使用"Evaluate in Console"功能可以在控制台中运行部分代码段. 请注意,Sourc ...
- 第1阶段——关于u-boot目标文件start.o中.globl 和.balignl理解(3)
汇编程序中以.开头的名称并不是指令的助记符,不会被翻译成机器指令,而是给汇编器一些特殊指示,称为伪操作. .globl _start 作用:声明一个_start全局符号(Symbol), 这个_sta ...
- ueditor ie8兼容性问题
ie8情况下,在进入加载有uEditor编辑器页面时候,不显示工具栏,会提示ueditor 缺少对象或者出现错误 1.引用Ueditor的js 的时候用 绝对路径 网上搜出来的一种解决 ...
- JS学习一
js中的变量输出 [使用JS的三种方式] 1. 在HTML标签中,直接内嵌JS(并不提倡使用): <button onclick="alert('你真点啊!')"> ...
- 201521123082《Java程序设计》第2周学习总结
201521123082<Java程序设计>第2周学习总结 标签(空格分隔): Java 1.本周学习总结 巩固了类型转换的相关细节 初步认识了类和对象,使用Java撰写程序几乎都在使用对 ...
- 201521123063 《Java程序设计》 第4周学习总结
1.本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 1.2 使用常规方法总结其他上课内容. 类设计 一般在设计类的时候,要考虑这些类是否有共性,还要考虑其独特性,使共同的父类拥有这些共性 ...