1.前言
Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基於內存亦可持久化的日志型、Key-Value數據庫,並提供多種語言的API。我們都知道,在日常的應用中,數據庫瓶頸是最容易出現的。數據量太大和頻繁的查詢,由於磁盤IO性能的局限性,導致項目的性能越來越低。這時候,基於內存的緩存框架,就能解決我們很多問題。例如Memcache,Redis等。將一些頻繁使用的數據放入緩存讀取,大大降低了數據庫的負擔。提升了系統的性能。
有於Memcached,對於緩存對象大小有要求,單個對象不得大於1MB,且不支持復雜的數據類型,譬如SET等。因此現在Redis用的越來越多。
2.引入依賴
<!-- jedis依賴 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.2.RELEASE</version> </dependency>
注意應該導入下面包
如果存儲的是Map<String,Object>需要導入jackson相關的包,存儲的時候使用json序列化器存儲。如果不導入jackson的包會報錯。
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.1.0</version> </dependency>
3.配置文件
3.1 redis.properties
#訪問地址
redis.host=127.0.0.1
#訪問端口
redis.port=6379
#注意,如果沒有password,此處不設置值,但這一項要保留
redis.password=
#最大空閑數,數據庫連接的最大空閑時間。超過空閑時間,數據庫連接將被標記為不可用,然后被釋放。設為0表示無限制。
redis.maxIdle=300
#連接池的最大數據庫連接數。設為0表示無限制
redis.maxActive=600
#最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。
redis.maxWait=1000
#在borrow一個jedis實例時,是否提前進行alidate操作;如果為true,則得到的jedis實例均是可用的;
redis.testOnBorrow=true
3.2applicationContext-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 連接池基本參數配置,類似數據庫連接池 --> <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" /> <!-- redis連接池 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis.maxActive}" /> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <!-- 連接池配置,類似數據庫連接池 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"></property> <property name="port" value="${redis.port}"></property> <!-- <property name="password" value="${redis.pass}"></property> --> <property name="poolConfig" ref="poolConfig"></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 > <!-- 下面這個是整合Mybatis的二級緩存使用的 --> <bean id="redisCacheTransfer" class="cn.qlq.jedis.RedisCacheTransfer"> <property name="jedisConnectionFactory" ref="jedisConnectionFactory" /> </bean> </beans>
注意事項:
如果在多個spring配置文件中引入<context:property-placeholder .../>標簽,最后需要加上ignore-unresolvable="true",否則會報錯。
JSON存儲的數據可以看懂,如果是其他序列化器序列化的看不懂。。。。。。
4.測試
package cn.qlq.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.qlq.util.RedisUtil; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext-*.xml") @SuppressWarnings("all") public class RedisTest { @Autowired private RedisUtil redisUtil; @Resource(name="redisTemplate") private RedisTemplate redisTemplate; @Test public void testSpringRedis() { // stringRedisTemplate的操作 // String讀寫 redisTemplate.delete("myStr"); redisTemplate.opsForValue().set("myStr", "skyLine"); System.out.println(redisTemplate.opsForValue().get("myStr")); System.out.println("---------------"); // List讀寫 redisTemplate.delete("myList"); redisTemplate.opsForList().rightPush("myList", "T"); redisTemplate.opsForList().rightPush("myList", "L"); redisTemplate.opsForList().leftPush("myList", "A"); List<String> listCache = redisTemplate.opsForList().range("myList", 0, -1); for (String s : listCache) { System.out.println(s); } System.out.println("---------------"); // Set讀寫 redisTemplate.delete("mySet"); redisTemplate.opsForSet().add("mySet", "A"); redisTemplate.opsForSet().add("mySet", "B"); redisTemplate.opsForSet().add("mySet", "C"); Set<String> setCache = redisTemplate.opsForSet().members("mySet"); for (String s : setCache) { System.out.println(s); } System.out.println("---------------"); // Hash讀寫 redisTemplate.delete("myHash"); redisTemplate.opsForHash().put("myHash", "BJ", "北京"); redisTemplate.opsForHash().put("myHash", "SH", "上海"); redisTemplate.opsForHash().put("myHash", "HN", "河南"); Map<String, String> hashCache = redisTemplate.opsForHash().entries("myHash"); for (Map.Entry entry : hashCache.entrySet()) { System.out.println(entry.getKey() + " - " + entry.getValue()); } System.out.println("---------------"); } }
結果:
skyLine
---------------
A
T
L
---------------
C
B
A
---------------
HN - 河南
BJ - 北京
SH - 上海
---------------
最后附加一個工具類:
RedisUtil.java(交給spring管理后在需要緩存的地方自動注入即可)
package cn.qlq.util; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; /** * * @author QLQ * 基於spring和redis的redisTemplate工具類 * 針對所有的hash 都是以h開頭的方法 * 針對所有的Set 都是以s開頭的方法 不含通用方法 * 針對所有的List 都是以l開頭的方法 */ @Component//交給Spring管理(在需要緩存的地方自動注入即可使用) public class RedisUtil { @Autowired//(自動注入redisTemplet) private RedisTemplate<String, Object> redisTemplate; public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } //=============================common============================ /** * 指定緩存失效時間 * @param key 鍵 * @param time 時間(秒) * @return */ public boolean expire(String key,long time){ try { if(time>0){ redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根據key 獲取過期時間 * @param key 鍵 不能為null * @return 時間(秒) 返回0代表為永久有效 */ public long getExpire(String key){ return redisTemplate.getExpire(key,TimeUnit.SECONDS); } /** * 判斷key是否存在 * @param key 鍵 * @return true 存在 false不存在 */ public boolean hasKey(String key){ try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 刪除緩存 * @param key 可以傳一個值 或多個 */ @SuppressWarnings("unchecked") public void del(String ... key){ if(key!=null&&key.length>0){ if(key.length==1){ redisTemplate.delete(key[0]); }else{ redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } //============================String============================= /** * 普通緩存獲取 * @param key 鍵 * @return 值 */ public Object get(String key){ return key==null?null:redisTemplate.opsForValue().get(key); } /** * 普通緩存放入 * @param key 鍵 * @param value 值 * @return true成功 false失敗 */ public boolean set(String key,Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通緩存放入並設置時間 * @param key 鍵 * @param value 值 * @param time 時間(秒) time要大於0 如果time小於等於0 將設置無限期 * @return true成功 false 失敗 */ public boolean set(String key,Object value,long time){ try { if(time>0){ redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); }else{ set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 遞增 * @param key 鍵 * @param by 要增加幾(大於0) * @return */ public long incr(String key, long delta){ if(delta<0){ throw new RuntimeException("遞增因子必須大於0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 遞減 * @param key 鍵 * @param by 要減少幾(小於0) * @return */ public long decr(String key, long delta){ if(delta<0){ throw new RuntimeException("遞減因子必須大於0"); } return redisTemplate.opsForValue().increment(key, -delta); } //================================Map================================= /** * HashGet * @param key 鍵 不能為null * @param item 項 不能為null * @return 值 */ public Object hget(String key,String item){ return redisTemplate.opsForHash().get(key, item); } /** * 獲取hashKey對應的所有鍵值 * @param key 鍵 * @return 對應的多個鍵值 */ public Map<Object,Object> hmget(String key){ return redisTemplate.opsForHash().entries(key); } /** * HashSet * @param key 鍵 * @param map 對應多個鍵值 * @return true 成功 false 失敗 */ public boolean hmset(String key, Map<String,Object> map){ try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 並設置時間 * @param key 鍵 * @param map 對應多個鍵值 * @param time 時間(秒) * @return true成功 false失敗 */ public boolean hmset(String key, Map<String,Object> map, long time){ try { redisTemplate.opsForHash().putAll(key, map); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一張hash表中放入數據,如果不存在將創建 * @param key 鍵 * @param item 項 * @param value 值 * @return true 成功 false失敗 */ public boolean hset(String key,String item,Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一張hash表中放入數據,如果不存在將創建 * @param key 鍵 * @param item 項 * @param value 值 * @param time 時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間 * @return true 成功 false失敗 */ public boolean hset(String key,String item,Object value,long time) { try { redisTemplate.opsForHash().put(key, item, value); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 刪除hash表中的值 * @param key 鍵 不能為null * @param item 項 可以使多個 不能為null */ public void hdel(String key, Object... item){ redisTemplate.opsForHash().delete(key,item); } /** * 判斷hash表中是否有該項的值 * @param key 鍵 不能為null * @param item 項 不能為null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item){ return redisTemplate.opsForHash().hasKey(key, item); } /** * hash遞增 如果不存在,就會創建一個 並把新增后的值返回 * @param key 鍵 * @param item 項 * @param by 要增加幾(大於0) * @return */ public double hincr(String key, String item,double by){ return redisTemplate.opsForHash().increment(key, item, by); } /** * hash遞減 * @param key 鍵 * @param item 項 * @param by 要減少記(小於0) * @return */ public double hdecr(String key, String item,double by){ return redisTemplate.opsForHash().increment(key, item,-by); } //============================set============================= /** * 根據key獲取Set中的所有值 * @param key 鍵 * @return */ public Set<Object> sGet(String key){ try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根據value從一個set中查詢,是否存在 * @param key 鍵 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key,Object value){ try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將數據放入set緩存 * @param key 鍵 * @param values 值 可以是多個 * @return 成功個數 */ public long sSet(String key, Object...values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 將set數據放入緩存 * @param key 鍵 * @param time 時間(秒) * @param values 值 可以是多個 * @return 成功個數 */ public long sSetAndTime(String key,long time,Object...values) { try { Long count = redisTemplate.opsForSet().add(key, values); if(time>0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 獲取set緩存的長度 * @param key 鍵 * @return */ public long sGetSetSize(String key){ try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值為value的 * @param key 鍵 * @param values 值 可以是多個 * @return 移除的個數 */ public long setRemove(String key, Object ...values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } //===============================list================================= /** * 獲取list緩存的內容 * @param key 鍵 * @param start 開始 * @param end 結束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key,long start, long end){ try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 獲取list緩存的長度 * @param key 鍵 * @return */ public long lGetListSize(String key){ try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通過索引 獲取list中的值 * @param key 鍵 * @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推 * @return */ public Object lGetIndex(String key,long index){ try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 將list放入緩存 * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 將list放入緩存 * @param key 鍵 * @param value 值 * @param time 時間(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根據索引修改list中的某條數據 * @param key 鍵 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index,Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N個值為value * @param key 鍵 * @param count 移除多少個 * @param value 值 * @return 移除的個數 */ public long lRemove(String key,long count,Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } }
如果不加注解,使用xml交給spring可以用下面方式:
<!--自定義redis工具類,在需要緩存的地方注入此類 --> <bean id="redisUtil" class="cn.qlq.util.RedisUtil"> <property name="redisTemplate" ref="redisTemplate" /> </bean>
- 測試工具類:
package cn.qlq.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.qlq.util.RedisUtil; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext-*.xml") @SuppressWarnings("all") public class RedisTest { @Autowired private RedisUtil redisUtil; @Test public void testSpringRedis2(){ String str = "string";//1.字符串 List<String> list = new ArrayList<String>();//list list.add("0"); list.add("中國"); list.add("2"); Set<String> set = new HashSet<String>();//set set.add("0"); set.add("中國"); set.add("2"); Map<String, Object> map = new HashMap();//map map.put("key1", "str1"); map.put("key2", "中國"); map.put("key3", "str3"); redisUtil.del("myStr","str");//刪除數據 //1.字符串操作 redisUtil.set("str", str); redisUtil.expire("str", 120);//指定失效時間為2分鍾 String str1 = (String) redisUtil.get("str"); System.out.println(str1); //2.list操作 redisUtil.lSet("list", list); redisUtil.expire("list", 120);//指定失效時間為2分鍾 List<Object> list1 = redisUtil.lGet("list", 0, -1); System.out.println(list1); //3.set操作 redisUtil.sSet("set", set); redisUtil.expire("set", 120);//指定失效時間為2分鍾 Set<Object> set1 = redisUtil.sGet("set"); System.out.println(set1); //3.map操作 redisUtil.hmset("map", map); redisUtil.expire("map", 120);//指定失效時間為2分鍾 Map<Object, Object> map1 = redisUtil.hmget("map"); System.out.println(map1); } }
結果:
通過redis客戶端查詢:
如果有需求設置緩存存活的時間可以在每個的set方法里面調用一下設置存活時間的方法,或者直接將存活時間參數傳下去,可以將存活時間的默認值放到配置文件或者常量類中。靈活的設置緩存時間。
- 測試工具類緩存JavaBean
1.被緩存的類需要實現序列化接口 Serializable
2.測試:
@Test public void testSpringRedis3(){ List<User> list = new ArrayList<User>();//list list.add(new User(1,"QLQ1")); list.add(new User(2,"QLQ2")); list.add(new User(3,"QLQ3")); Set<User> set = new HashSet<User>();//set set.add(new User(1,"QLQ1")); set.add(new User(2,"QLQ2")); set.add(new User(3,"QLQ3")); Map<String, Object> map = new HashMap();//map map.put("key1", new User(1,"QLQ1")); map.put("key2", new User(1,"QLQ2")); map.put("key3", new User(1,"QLQ3")); //2.list操作 redisUtil.lSet("list", list,1200); List<Object> list1 = redisUtil.lGet("list", 0, -1); System.out.println(list1); //3.set操作 redisUtil.sSet("set", set); redisUtil.expire("set", 1200);//指定失效時間為2分鍾 Set<Object> set1 = redisUtil.sGet("set"); System.out.println(set1); //3.map操作 redisUtil.hmset("map", map); redisUtil.expire("map", 120);//指定失效時間為2分鍾 Map<Object, Object> map1 = redisUtil.hmget("map"); System.out.println(map1); }
結果:
redis客戶端查看緩存數據:
總結:
在redis做緩存的時候最好是每個緩存的生命周期不固定,也就是分散的使緩存失效。可以設置有效期為3-9小時。具體的做法就是在Java中產生一個3-9小時的隨機數。
參考;
http://blog.csdn.net/tomcat_2014/article/details/55260306
有redis集群的配置: http://blog.csdn.net/qq_34021712/article/details/75949706
spring注解緩存集成redis配置: http://www.cnblogs.com/qlqwjy/p/8574121.html