數據緩存原因:有些數據比較多,如果每次訪問都要進行查詢,無疑給數據庫帶來太大的負擔,將一些龐大的查詢數據并且更新次數較少的數據存入redis,能為系統的性能帶來良好的提升。
業務邏輯思路:登入系統,訪問數據時,檢查redis是否有緩存,有則直接從redis中提取,沒有則從數據庫查詢出,并存入redis中做緩存。
為什么要用redis做緩存:
(1)異??焖伲篟edis的速度非???,每秒能執行約11萬集合,每秒約81000+條記錄。
(2)支持豐富的數據類型:Redis支持最大多數開發人員已經知道像列表,集合,有序集合,散列數據類型。這使得它非常容易解決各種各樣的問題,因為我們知道哪些問題是可以處理通過它的數據類型更好。
(3)操作都是原子性:所有Redis操作是原子的,這保證了如果兩個客戶端同時訪問的Redis服務器將獲得更新后的值。
(4)多功能實用工具:Redis是一個多實用的工具,可以在多個用例如緩存,消息,隊列使用(Redis原生支持發布/訂閱),任何短暫的數據,應用程序,如Web應用程序會話,網頁命中計數等。
緩存實現思路:
一、項目中配置好redis賬戶等屬性文件(redis.properties)
#ip地址redis.hostName=yourIpAddress#端口號redis.port=6379#如果有密碼redis.password=yourRedisPassword#客戶端超時時間單位是毫秒 默認是2000redis.timeout=10000 #最大空閑數redis.maxIdle=300#連接池的最大數據庫連接數。設為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#每次釋放連接的最大數目,默認3redis.numTestsPerEvictionRun=1024#逐出掃描的時間間隔(毫秒) 如果為負數,則不運行逐出線程, 默認-1redis.timeBetweenEvictionRunsMillis=30000#是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接并嘗試取出另一個redis.testOnBorrow=true#在空閑時檢查有效性, 默認falseredis.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" > <!--最大空閑數--> <property name="maxIdle" value="${redis.maxIdle}" /> <!--連接池的最大數據庫連接數 --> <property name="maxTotal" value="${redis.maxTotal}" /> <!--最大建立連接等待時間--> <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> <!--逐出連接的最小空閑時間 默認1800000毫秒(30分鐘)--> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" /> <!--每次逐出檢查時 逐出的最大數目 如果為負數就是 : 1/abs(n), 默認3--> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" /> <!--逐出掃描的時間間隔(毫秒) 如果為負數,則不運行逐出線程, 默認-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工具類 * :用于緩存數據 * */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("系統異常",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("系統異常",e); } return result; }}
注意點:redis工具類由spring進行托管,則在需要緩存的地方注入redis工具類即可。
總結
以上所述是小編給大家介紹的spring整合redis實現數據緩存的實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答
圖片精選