最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

windows環(huán)境下Redis+Spring緩存實例講解

 更新時間:2016年04月20日 16:36:17   投稿:lijiao  
這篇文章主要為大家詳細介紹了windows環(huán)境下Redis+Spring緩存實例教程,感興趣的小伙伴們可以參考一下

一、Redis了解

1.1、Redis介紹:

redis是一個key-value存儲系統(tǒng)。和Memcached類似,它支持存儲的value類型相對更多,包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set –有序集合)和hash(哈希類型)。這些數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。區(qū)別的是redis會周期性的把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎上實現(xiàn)了master-slave(主從)同步。

Redis數(shù)據(jù)庫完全在內(nèi)存中,使用磁盤僅用于持久性。相比許多鍵值數(shù)據(jù)存儲,Redis擁有一套較為豐富的數(shù)據(jù)類型。Redis可以將數(shù)據(jù)復制到任意數(shù)量的從服務器。

1.2、Redis優(yōu)點:

(1)異常快速:Redis的速度非??欤棵肽軋?zhí)行約11萬集合,每秒約81000+條記錄。

(2)支持豐富的數(shù)據(jù)類型:Redis支持最大多數(shù)開發(fā)人員已經(jīng)知道像列表,集合,有序集合,散列數(shù)據(jù)類型。這使得它非常容易解決各種各樣的問題,因為我們知道哪些問題是可以處理通過它的數(shù)據(jù)類型更好。

(3)操作都是原子性:所有Redis操作是原子的,這保證了如果兩個客戶端同時訪問的Redis服務器將獲得更新后的值。

(4)多功能實用工具:Redis是一個多實用的工具,可以在多個用例如緩存,消息,隊列使用(Redis原生支持發(fā)布/訂閱),任何短暫的數(shù)據(jù),應用程序,如Web應用程序會話,網(wǎng)頁命中計數(shù)等。

1.3、Redis缺點:

(1)單線程

(2)耗內(nèi)存

二、64位windows下Redis安裝

Redis官方是不支持windows的,但是Microsoft Open Tech group 在 GitHub上開發(fā)了一個Win64的版本,下載地址:https://github.com/MSOpenTech/redis/releases。注意只支持64位哈。

小寶鴿是下載了Redis-x64-3.0.500.msi進行安裝。安裝過程中全部采取默認即可。

安裝完成之后可能已經(jīng)幫你開啟了Redis對應的服務,博主的就是如此。查看資源管理如下,說明已經(jīng)開啟:

已經(jīng)開啟了對應服務的,我們讓它保持,下面例子需要用到。如果沒有開啟的,我們命令開啟,進入Redis的安裝目錄(博主的是C:\Program Files\Redis),然后如下命令開啟:

redis-server  redis.windows.conf

OK,下面我們進行實例。

三、詳細實例

本工程采用的環(huán)境: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>
    <!--要是有多個配置文件,只需在這里繼續(xù)添加即可 -->
   </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配置參數(shù),redis.properties:

#redis中心
#綁定的主機地址
redis.host=127.0.0.1
#指定Redis監(jiān)聽端口,默認端口為6379
redis.port=6379
#授權密碼(本例子沒有使用)
redis.password=123456 
#最大空閑數(shù):空閑鏈接數(shù)大于maxIdle時,將進行回收
redis.maxIdle=100 
#最大連接數(shù):能夠同時建立的“最大鏈接個數(shù)”
redis.maxActive=300 
#最大等待時間:單位ms
redis.maxWait=1000 
#使用連接時,檢測連接是否成功 
redis.testOnBorrow=true
#當客戶端閑置多長時間后關閉連接,如果指定為0,表示關閉該功能
redis.timeout=10000

3.4、添加接口及對應實現(xiàn)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配置文件中,對應實現(xiàn)為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;
 }
 
 /**
  * 創(chuàng)建緩存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("第一次調(diào)用:" + redisTestService.getTimestamp("param"));
  Thread.sleep(2000);
  System.out.println("2秒之后調(diào)用:" + redisTestService.getTimestamp("param"));
  Thread.sleep(11000);
  System.out.println("再過11秒之后調(diào)用:" + redisTestService.getTimestamp("param"));
 } 
}

3.7、運行結果:

四、源碼下載:redis-project(jb51.net).rar

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。

相關文章

  • Redis批量刪除key的命令詳解

    Redis批量刪除key的命令詳解

    這篇文章主要介紹了Redis批量刪除key的命令詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Redis解決跨域存取Session問題

    Redis解決跨域存取Session問題

    本文主要介紹了Redis解決跨域存取Session問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-04-04
  • Redis不使用 keys 命令獲取鍵值信息的方法

    Redis不使用 keys 命令獲取鍵值信息的方法

    這篇文章主要介紹了Redis 不使用 keys 命令獲取鍵值信息的相關知識,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧
    2018-08-08
  • Redis實現(xiàn)布隆過濾器的方法及原理

    Redis實現(xiàn)布隆過濾器的方法及原理

    布隆過濾器優(yōu)點是空間效率和查詢時間都比一般的算法要好的多,缺點是有一定的誤識別率和刪除困難。本文將介紹布隆過濾器的原理以及Redis如何實現(xiàn)布隆過濾器,感興趣的朋友跟隨小編一起看看吧
    2019-12-12
  • redis中hash表內(nèi)容刪除的方法代碼

    redis中hash表內(nèi)容刪除的方法代碼

    在本篇文章里小編給各位整理了關于redis中hash表內(nèi)容怎么刪除的方法以及技巧代碼,需要的朋友們分享下。
    2019-07-07
  • Redis設置密碼的實現(xiàn)步驟

    Redis設置密碼的實現(xiàn)步驟

    本文主要介紹了Redis設置密碼的實現(xiàn)步驟,主要包括兩種方法:臨時密碼和持久密碼,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • redis redistemplate序列化對象配置方式

    redis redistemplate序列化對象配置方式

    這篇文章主要介紹了redis redistemplate序列化對象配置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Win10下通過Ubuntu安裝Redis的過程

    Win10下通過Ubuntu安裝Redis的過程

    這篇文章主要介紹了Win10下通過Ubuntu安裝Redis,在安裝Ubuntu需要先打開Windows功能,接著創(chuàng)建一個用戶及密碼,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • RedisTemplate批量操作工具類性能測試

    RedisTemplate批量操作工具類性能測試

    這篇文章主要為大家介紹了RedisTemplate批量操作工具類性能測試詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • Redisson如何解決Redis分布式鎖提前釋放問題

    Redisson如何解決Redis分布式鎖提前釋放問題

    本文主要介紹了Redisson如何解決Redis分布式鎖提前釋放問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-05-05

最新評論

湘乡市| 永和县| 赞皇县| 灵山县| 无极县| 屏东市| 平山县| 兰溪市| 庆云县| 炎陵县| 西昌市| 尼勒克县| 时尚| 会昌县| 垫江县| 边坝县| 临潭县| 安塞县| 琼结县| 华安县| 五寨县| 太原市| 汾阳市| 黄冈市| 武定县| 华蓥市| 项城市| 德清县| 军事| 那曲县| 廉江市| 邵武市| 巫山县| 铜山县| 南漳县| 卢龙县| 姜堰市| 麻栗坡县| 阜新市| 朝阳县| 瑞金市|