spring整合redis實現(xiàn)數(shù)據(jù)緩存的實例代碼
數(shù)據(jù)緩存原因:有些數(shù)據(jù)比較多,如果每次訪問都要進行查詢,無疑給數(shù)據(jù)庫帶來太大的負擔,將一些龐大的查詢數(shù)據(jù)并且更新次數(shù)較少的數(shù)據(jù)存入redis,能為系統(tǒng)的性能帶來良好的提升。
業(yè)務(wù)邏輯思路:登入系統(tǒng),訪問數(shù)據(jù)時,檢查redis是否有緩存,有則直接從redis中提取,沒有則從數(shù)據(jù)庫查詢出,并存入redis中做緩存。
為什么要用redis做緩存:
(1)異常快速:Redis的速度非???,每秒能執(zhí)行約11萬集合,每秒約81000+條記錄。
(2)支持豐富的數(shù)據(jù)類型:Redis支持最大多數(shù)開發(fā)人員已經(jīng)知道像列表,集合,有序集合,散列數(shù)據(jù)類型。這使得它非常容易解決各種各樣的問題,因為我們知道哪些問題是可以處理通過它的數(shù)據(jù)類型更好。
(3)操作都是原子性:所有Redis操作是原子的,這保證了如果兩個客戶端同時訪問的Redis服務(wù)器將獲得更新后的值。
(4)多功能實用工具:Redis是一個多實用的工具,可以在多個用例如緩存,消息,隊列使用(Redis原生支持發(fā)布/訂閱),任何短暫的數(shù)據(jù),應(yīng)用程序,如Web應(yīng)用程序會話,網(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ù)。設(shè)為0表示無限制,如果是jedis 2.4以后用redis.maxTotal #redis.maxActive=600 #控制一個pool可分配多少個jedis實例,用來替換上面的redis.maxActive,如果是jedis 2.4以后用該屬性 redis.maxTotal=1000 #最大建立連接等待時間。如果超過此時間將接到異常。設(shè)為-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設(shè)置有密碼 --> <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> <!--開啟事務(wù) --> <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; } /** * 批量刪除對應(yīng)的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); } } /** * 刪除對應(yīng)的value * * @param key */ public void remove(final String key) { logger.info("要移除的key為:" + key); if (exists(key)) { redisTemplate.delete(key); } } /** * 判斷緩存中是否有對應(yīng)的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ù)緩存的實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
Java請求轉(zhuǎn)發(fā)和請求重定向區(qū)別詳解
這篇文章主要介紹了Java請求轉(zhuǎn)發(fā)和請求重定向區(qū)別詳解,請求轉(zhuǎn)發(fā)和請求重定向,但二者是完全不同的,所以我們今天就來盤他們的區(qū)別介紹,需要的朋友可以參考一下2022-07-07Mybatis Plus Wrapper查詢某幾列的方法實現(xiàn)
MybatisPlus中,使用Wrapper的select和notSelect方法可以精確控制查詢的字段,本文就來介紹一下Mybatis Plus Wrapper查詢某幾列的方法實現(xiàn),感興趣的可以了解一下2024-10-10