Redis+Spring缓存实例
转自:小宝鸽
一、Redis了解
1.1、Redis介绍:
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
Redis数据库完全在内存中,使用磁盘仅用于持久性。相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。Redis可以将数据复制到任意数量的从服务器。
1.2、Redis优点:
(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。
1.3、Redis缺点:
(1)单线程
(2)耗内存
二、64位windows下Redis安装
Redis官方是不支持windows的,但是Microsoft Open Tech group 在 GitHub上开发了一个Win64的版本,下载地址:https://github.com/MSOpenTech/redis/releases。注意只支持64位哈。
小宝鸽是下载了Redis-x64-3.0.500.msi进行安装。安装过程中全部采取默认即可。
安装完成之后可能已经帮你开启了Redis对应的服务,博主的就是如此。查看资源管理如下,说明已经开启:

已经开启了对应服务的,我们让它保持,下面例子需要用到。如果没有开启的,我们命令开启,进入Redis的安装目录(博主的是C:\Program Files\Redis),然后如下命令开启:
redis-server redis.windows.conf

OK,下面我们进行实例。
三、详细实例
本工程采用的环境:eclipse + maven + spring + junit
3.1、添加相关依赖(spring+junit+redis依赖),pom.xml:
- <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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.luo</groupId>
- <artifactId>redis_project</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <properties>
- <!-- spring版本号 -->
- <spring.version>3.2.8.RELEASE</spring.version>
- <!-- junit版本号 -->
- <junit.version>4.10</junit.version>
- </properties>
- <dependencies>
- <!-- 添加Spring依赖 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</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-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</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-aspects</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!--单元测试依赖 -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- <scope>test</scope>
- </dependency>
- <!--spring单元测试依赖 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- <!-- 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>
- </dependencies>
- </project>
pom.xml
3.2、spring配置文件application.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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!-- 自动扫描注解的bean -->
- <context:component-scan base-package="com.luo.service" />
- <!-- 引入properties配置文件 -->
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:properties/*.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 >
- <!-- cache配置 -->
- <bean id="methodCacheInterceptor" class="com.luo.redis.cache.MethodCacheInterceptor" >
- <property name="redisTemplate" ref="redisTemplate" />
- </bean >
- <!-- aop配置切点跟通知 -->
- <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
- <property name="advice" ref="methodCacheInterceptor"/>
- <property name="pattern" value=".*ServiceImpl.*getTimestamp"/>
- </bean>
- <bean id="redisTestService" class="com.luo.service.impl.RedisTestServiceImpl">
- </bean>
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
- </beans>
application.xml
3.3、Redis配置参数,redis.properties:
- #redis中心
- #绑定的主机地址
- redis.host=127.0.0.1
- #指定Redis监听端口,默认端口为6379
- redis.port=6379
- #授权密码(本例子没有使用)
- redis.password=123456
- #最大空闲数:空闲链接数大于maxIdle时,将进行回收
- redis.maxIdle=100
- #最大连接数:能够同时建立的“最大链接个数”
- redis.maxActive=300
- #最大等待时间:单位ms
- redis.maxWait=1000
- #使用连接时,检测连接是否成功
- redis.testOnBorrow=true
- #当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
- redis.timeout=10000
redis.properties
3.4、添加接口及对应实现RedisTestService.java和RedisTestServiceImpl.java:
- package com.luo.service;
- public interface RedisTestService {
- public String getTimestamp(String param);
- }
RedisTestService.java
3.5、本例采用spring aop切面方式进行缓存,配置已在上面spring配置文件中,对应实现为MethodCacheInterceptor.java:
- package com.luo.redis.cache;
- import java.io.Serializable;
- import java.util.concurrent.TimeUnit;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.core.ValueOperations;
- public class MethodCacheInterceptor implements MethodInterceptor {
- private RedisTemplate<Serializable, Object> redisTemplate;
- private Long defaultCacheExpireTime = 10l; // 缓存默认的过期时间,这里设置了10秒
- public Object invoke(MethodInvocation invocation) throws Throwable {
- Object value = null;
- String targetName = invocation.getThis().getClass().getName();
- String methodName = invocation.getMethod().getName();
- Object[] arguments = invocation.getArguments();
- String key = getCacheKey(targetName, methodName, arguments);
- try {
- // 判断是否有缓存
- if (exists(key)) {
- return getCache(key);
- }
- // 写入缓存
- value = invocation.proceed();
- if (value != null) {
- final String tkey = key;
- final Object tvalue = value;
- new Thread(new Runnable() {
- public void run() {
- setCache(tkey, tvalue, defaultCacheExpireTime);
- }
- }).start();
- }
- } catch (Exception e) {
- e.printStackTrace();
- if (value == null) {
- return invocation.proceed();
- }
- }
- return value;
- }
- /**
- * 创建缓存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();
- }
- /**
- * 判断缓存中是否有对应的value
- *
- * @param key
- * @return
- */
- public boolean exists(final String key) {
- return redisTemplate.hasKey(key);
- }
- /**
- * 读取缓存
- *
- * @param key
- * @return
- */
- public Object getCache(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 setCache(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;
- }
- }
MethodCacheInterceptor.java
3.6、单元测试相关类:
- package com.luo.baseTest;
- import org.junit.runner.RunWith;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- //指定bean注入的配置文件
- @ContextConfiguration(locations = { "classpath:application.xml" })
- //使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
- @RunWith(SpringJUnit4ClassRunner.class)
- public class SpringTestCase extends AbstractJUnit4SpringContextTests {
- }
SpringTestCase.java
- package com.luo.service;
- import org.junit.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import com.luo.baseTest.SpringTestCase;
- public class RedisTestServiceTest extends SpringTestCase {
- @Autowired
- private RedisTestService redisTestService;
- @Test
- public void getTimestampTest() throws InterruptedException{
- System.out.println("第一次调用:" + redisTestService.getTimestamp("param"));
- Thread.sleep(2000);
- System.out.println("2秒之后调用:" + redisTestService.getTimestamp("param"));
- Thread.sleep(11000);
- System.out.println("再过11秒之后调用:" + redisTestService.getTimestamp("param"));
- }
- }
RedisTestServiceTest
3.7、运行结果:

四、源码下载
http://download.csdn.net/detail/u013142781/9403316
Redis+Spring缓存实例的更多相关文章
- Redis+Spring缓存实例(windows环境,附实例源码及详解)
原文出处: 小宝鸽 一.Redis了解 1.1.Redis介绍: redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串). ...
- Echache整合Spring缓存实例讲解(转)
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要介绍了EhCache,并通过整合Spring给出了一个使用实例. 一.EhCac ...
- Jedis+Redis+spring缓存
Redis程序使用它?Jedis 访问redis java api Redis-server & //后台运行防火墙要关闭 ts-parent的pom.xml加上jedis依赖 <dep ...
- Echache整合Spring缓存实例解说
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要介绍了EhCache,并通过整合Spring给出了一个使用实例. 一.EhCac ...
- Echache整合Spring缓存实例讲解
摘要:本文主要介绍了EhCache,并通过整合Spring给出了一个使用实例. 一.EhCache 介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中 ...
- spring+redis的集成,redis做缓存
1.前言 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.我们都知道,在日常的应用中,数据库瓶颈是最容易出现的 ...
- spring配置redis注解缓存
前几天在spring整合Redis的时候使用了手动的方式,也就是可以手动的向redis添加缓存与清除缓存,参考:http://www.cnblogs.com/qlqwjy/p/8562703.html ...
- Spring boot配置多个Redis数据源操作实例
原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...
- Spring Boot 整合 Redis 实现缓存操作
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 ...
随机推荐
- java 计算地球上两点间距离
/** * 计算地球上任意两点(经纬度)距离 * * @param long1 * 第一点经度 * @param lat1 * 第一点纬度 * @param long2 * 第二点经度 * @para ...
- 总有一天会NB的! SB一样的坚持会有NB一样的结果的!
第一天: 1.背景图不显示,因为背景图片无法撑开div,所以必须自己设置div的高度哦! 2.div水平居中! A:margin-left:auto;margin-right:auto; B: 父元 ...
- 怎样设置Word下次打开时跳转到上次阅读的位置
①我们启动Word2013,打开需要阅读的文档,当阅读完毕之后,在指定位置键入一个空格,然后按下Delete键删除,这样相当于是没有作任何更改. ②保存文档,单击文件--另存为,选择好路径,将文档保存 ...
- 线性表的顺序存储结构C语言版
#include <stdio.h> #define MAXSIZE 101 #define N 10 typedef struct SeqList { int data[MAXSIZE] ...
- JVM垃圾收集器介绍
垃圾回收算法是GC的方法论,垃圾收集器就是内存回收的具体实现. 一.Serial 收集器 单线程收集器,在进行GC时,必须暂停所有的工作线程(Stop The World),直到GC收集结束. 缺点: ...
- 手把手windows64位配置安装python2.7
这几天公司要用到python的一些算法,让我调研一番,之前对Python一次没接触的我在安装配置环境的时候由于版本的问题,折腾了好久,这里简单介绍一下我的安装方法,需要安装pyhton的朋友可以不再向 ...
- lucene-查询query->TermQuery按词条搜索
TermQuery是最简单.也是最常用的Query.TermQuery可以理解成为“词条搜索”,在搜索引擎中最基本的搜索就是在索引中搜索某一词条,而TermQuery就是用来完成这项工作的. 在Lu ...
- js-读取上传文件后缀
/** * 读取文件后缀名称,并转化成小写 * @param file_name * @returns */ function houzuiToLowerCase(file_name) { if (f ...
- 数组与指针-----a[i]=*(a+i)=i[a]
#include<stdio.h> #include<stdlib.h> int main(void) { ,,,,};//a[i]相当于*(a+i) printf(]); p ...
- Linux 爬虫
curl https://www.msi.umn.edu/tutorial-materials >tmp.txt perl -alne '{/(https.*?pdf)/;print $1 if ...