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

spring整合redis實現(xiàn)數(shù)據(jù)緩存的實例代碼

 更新時間:2018年09月16日 15:38:26   作者:chenjianzhou107  
這篇文章主要介紹了spring整合redis實現(xiàn)數(shù)據(jù)緩存,需要的朋友可以參考下

數(shù)據(jù)緩存原因:有些數(shù)據(jù)比較多,如果每次訪問都要進行查詢,無疑給數(shù)據(jù)庫帶來太大的負擔,將一些龐大的查詢數(shù)據(jù)并且更新次數(shù)較少的數(shù)據(jù)存入redis,能為系統(tǒng)的性能帶來良好的提升。

業(yè)務邏輯思路:登入系統(tǒng),訪問數(shù)據(jù)時,檢查redis是否有緩存,有則直接從redis中提取,沒有則從數(shù)據(jù)庫查詢出,并存入redis中做緩存。

為什么要用redis做緩存:

(1)異??焖伲篟edis的速度非??欤棵肽軋?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ù)等。

緩存實現(xiàn)思路:

  • 項目中配置好redis賬戶等屬性文件(redis.properties)
  • 整合到spring容器中(application-redis.xml)
  • 編寫redis工具類

一、項目中配置好redis賬戶等屬性文件(redis.properties)

#ip地址
redis.hostName=yourIpAddress
#端口號
redis.port=6379
#如果有密碼
redis.password=yourRedisPassword
#客戶端超時時間單位是毫秒 默認是2000
redis.timeout=10000 
#最大空閑數(shù)
redis.maxIdle=300
#連接池的最大數(shù)據(jù)庫連接數(shù)。設為0表示無限制,如果是jedis 2.4以后用redis.maxTotal
#redis.maxActive=600
#控制一個pool可分配多少個jedis實例,用來替換上面的redis.maxActive,如果是jedis 2.4以后用該屬性
redis.maxTotal=1000
#最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。
redis.maxWaitMillis=1000
#連接的最小空閑時間 默認1800000毫秒(30分鐘)
redis.minEvictableIdleTimeMillis=300000
#每次釋放連接的最大數(shù)目,默認3
redis.numTestsPerEvictionRun=1024
#逐出掃描的時間間隔(毫秒) 如果為負數(shù),則不運行逐出線程, 默認-1
redis.timeBetweenEvictionRunsMillis=30000
#是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接并嘗試取出另一個
redis.testOnBorrow=true
#在空閑時檢查有效性, 默認false
redis.testWhileIdle=true

二、整合到spring容器中(application-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:p="http://www.springframework.org/schema/p"  
  xmlns:context="http://www.springframework.org/schema/context"  
  xmlns:mvc="http://www.springframework.org/schema/mvc"  
  xmlns:cache="http://www.springframework.org/schema/cache" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc.xsd 
            http://www.springframework.org/schema/cache  
            http://www.springframework.org/schema/cache/spring-cache.xsd
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 加載配置文件 -->
  <context:property-placeholder ignore-unresolvable="true" location="classpath:properties/redis.properties" />
  <!-- redis連接池配置--> 
  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" > 
    <!--最大空閑數(shù)--> 
    <property name="maxIdle" value="${redis.maxIdle}" /> 
    <!--連接池的最大數(shù)據(jù)庫連接數(shù) -->
    <property name="maxTotal" value="${redis.maxTotal}" />
    <!--最大建立連接等待時間--> 
    <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> 
    <!--逐出連接的最小空閑時間 默認1800000毫秒(30分鐘)-->
    <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" /> 
    <!--每次逐出檢查時 逐出的最大數(shù)目 如果為負數(shù)就是 : 1/abs(n), 默認3-->
    <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" /> 
    <!--逐出掃描的時間間隔(毫秒) 如果為負數(shù),則不運行逐出線程, 默認-1-->
    <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" /> 
    <!--是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接并嘗試取出另一個--> 
    <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 
    <!--在空閑時檢查有效性, 默認false -->
    <property name="testWhileIdle" value="${redis.testWhileIdle}" /> 
  </bean >
  <!--redis連接工廠 -->
  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> 
    <property name="poolConfig" ref="jedisPoolConfig"></property> 
    <!--IP地址 -->
    <property name="hostName" value="${redis.hostName}"></property> 
    <!--端口號 -->
    <property name="port" value="${redis.port}"></property> 
    <!--如果Redis設置有密碼 -->
    <property name="password" value="${redis.password}" />
    <!--客戶端超時時間單位是毫秒 -->
    <property name="timeout" value="${redis.timeout}"></property> 
  </bean> 
  <!--redis操作模版,使用該對象可以操作redis -->
  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" > 
    <property name="connectionFactory" ref="jedisConnectionFactory" /> 
    <!--如果不配置Serializer,那么存儲的時候缺省使用String,如果用User類型存儲,那么會提示錯誤User can't cast to String?。?--> 
    <property name="keySerializer" > 
      <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="valueSerializer" > 
      <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" /> 
    </property> 
    <property name="hashKeySerializer"> 
      <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> 
    </property> 
    <property name="hashValueSerializer"> 
      <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> 
    </property> 
    <!--開啟事務 -->
    <property name="enableTransactionSupport" value="true"></property>
  </bean > 
  <!--自定義redis工具類,在需要緩存的地方注入此類 -->
  <bean id="redisUtil" class="com.neuedu.crm.utils.RedisUtil">
    <property name="redisTemplate" ref="redisTemplate" />
  </bean> 
</beans>

三、編寫redis工具類

package com.neuedu.crm.utils;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
/**
 * Redis工具類
 * :用于緩存數(shù)據(jù)
 *
 */
public class RedisUtil {
  private Logger logger = LoggerFactory.getLogger(RedisUtil.class);
  private RedisTemplate<Serializable, Object> redisTemplate;
  public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
    this.redisTemplate = 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) {
    logger.info("要移除的key為:" + key);
    if (exists(key)) {
      redisTemplate.delete(key);
    }
  }
  /**
   * 判斷緩存中是否有對應的value
   *
   * @param key
   * @return
   */
  public boolean exists(final String key) {
    logger.info("要驗證是否存在的key為:" + 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) {
      logger.error("系統(tǒng)異常",e);
    }
    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) {
      logger.error("系統(tǒng)異常",e);
    }
    return result;
  }
}

注意點:redis工具類由spring進行托管,則在需要緩存的地方注入redis工具類即可。

總結(jié)

以上所述是小編給大家介紹的spring整合redis實現(xiàn)數(shù)據(jù)緩存的實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

相關文章

  • springboot如何配置允許跨域訪問

    springboot如何配置允許跨域訪問

    這篇文章主要介紹了springboot如何配置允許跨域訪問,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 淺談Mybatis+mysql 存儲Date類型的坑

    淺談Mybatis+mysql 存儲Date類型的坑

    這篇文章主要介紹了淺談Mybatis+mysql 存儲Date類型的坑,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • 淺談springBean的作用域

    淺談springBean的作用域

    本文主要介紹了淺談springBean的作用域,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • Java并發(fā)編程深入理解之Synchronized的使用及底層原理詳解 下

    Java并發(fā)編程深入理解之Synchronized的使用及底層原理詳解 下

    在并發(fā)編程中存在線程安全問題,主要原因有:1.存在共享數(shù)據(jù) 2.多線程共同操作共享數(shù)據(jù)。關鍵字synchronized可以保證在同一時刻,只有一個線程可以執(zhí)行某個方法或某個代碼塊,同時synchronized可以保證一個線程的變化可見(可見性),即可以代替volatile
    2021-09-09
  • 基于RestTemplate的使用方法(詳解)

    基于RestTemplate的使用方法(詳解)

    下面小編就為大家?guī)硪黄赗estTemplate的使用方法(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • JAVA面試題 從源碼角度分析StringBuffer和StringBuilder的區(qū)別

    JAVA面試題 從源碼角度分析StringBuffer和StringBuilder的區(qū)別

    這篇文章主要介紹了JAVA面試題 從源碼角度分析StringBuffer和StringBuilder的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,下面我們來一起學習下吧
    2019-07-07
  • Spring實戰(zhàn)之注入集合值操作示例

    Spring實戰(zhàn)之注入集合值操作示例

    這篇文章主要介紹了Spring實戰(zhàn)之注入集合值操作,結(jié)合實例形式分析了Spring注入集合值相關配置及使用操作技巧,需要的朋友可以參考下
    2019-11-11
  • 使用Spring實現(xiàn)@Value注入靜態(tài)字段

    使用Spring實現(xiàn)@Value注入靜態(tài)字段

    這篇文章主要介紹了使用Spring實現(xiàn)@Value注入靜態(tài)字段方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Spring中@Conditional注解用法詳解

    Spring中@Conditional注解用法詳解

    這篇文章主要介紹了Spring中@Conditional注解用法詳解,@Conditional是Spring4版本新提供的一種注解,它的作用是按照設定的條件進行判斷,把滿足判斷條件的bean注冊到Spring容器,需要的朋友可以參考下
    2023-11-11
  • Java中的泛型詳細解析

    Java中的泛型詳細解析

    這篇文章主要介紹了Java中的泛型詳細解析,泛型又稱參數(shù)化類型,是JDK5.0出現(xiàn)的新特性,解決了數(shù)據(jù)類型的安全型問題,Java泛型可以保證如果程序在編譯時沒用發(fā)出警告,運行時就不會產(chǎn)生classCastException異常,需要的朋友可以參考下
    2024-01-01

最新評論

宜良县| 延庆县| 新建县| 普宁市| 长武县| 寿光市| 柯坪县| 平遥县| 北辰区| 博客| 长垣县| 丹阳市| 安溪县| 象州县| 沅陵县| 房产| 诸暨市| 青州市| 呼和浩特市| 宁远县| 林口县| 嘉黎县| 广宁县| 会理县| 唐海县| 上虞市| 札达县| 皋兰县| 大安市| 肃宁县| 郧西县| 花莲县| 班戈县| 通海县| 交口县| 柞水县| 崇仁县| 大城县| 北宁市| 平武县| 长武县|