当前位置: 移动技术网 > IT编程>数据库>Redis > windows环境下Redis+Spring缓存实例讲解

windows环境下Redis+Spring缓存实例讲解

2017年12月08日  | 移动技术网IT编程  | 我要评论
一、redis了解 1.1、redis介绍: redis是一个key-value存储系统。和memcached类似,它支持存储的value类型相对更多,包括string

一、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>

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>

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

3.4、添加接口及对应实现redistestservice.java和redistestserviceimpl.java:

package com.luo.service;
 
public interface redistestservice {
 public string gettimestamp(string param);
}
package com.luo.service.impl;
 
import org.springframework.stereotype.service;
import com.luo.service.redistestservice;
 
@service
public class redistestserviceimpl implements redistestservice {
 
 public string gettimestamp(string param) {
  long timestamp = system.currenttimemillis();
  return timestamp.tostring();
 }
 
}


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;
 }
}


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 {
 
}
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"));
 } 
}

3.7、运行结果:

四、源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网