什麼是Redis?
Remote Dictionary Server(Redis) 遠程字典服務器是完全開源免費的,用C語言編寫的,遵守BSD開源協議,是一個高性能的(key/value)分佈式內存數據庫,基於內存運行,並支持持久化的NoSQL數據庫,它也通常被稱爲數據結構服務器,因爲值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型。
與傳統數據庫不同的是 Redis 的數據是存在內存中的,所以存寫速度非常快,因此 Redis 被廣泛應用於緩存方向。Redis爲分佈式緩存,在多實例的情況下,各實例共用一份緩存數據,緩存具有一致性。
Rediis 與其他 key - value 緩存產品有以下三個特點:
性能極高 – Redis讀的速度是11W次/s,寫的速度是81K次/s
支持數據的持久化,可以將內存中的數據保存在磁盤中,重啓的時候可以再次加載進行使用。
豐富的數據類型,Redis不僅僅支持簡單的key-value類型的數據,同時還提供Strings, Lists, Hashes, Sets 及 Ordered Sets 等數據結構的存儲。
支持數據的備份,即master-slave模式的數據備份。
Redis使用場景,查詢出的數據保存到Redis中,下次查詢的時候直接從Redis中拿到數據。不用和數據庫進行交互。
什麼數據會存到redis數據庫中?
主要是熱點數據,不會經常改變的,一般是常量
比如登錄驗證的cookie,購物車,歷史瀏覽記錄都(只要具有一定時間的生命週期)
比如首頁的商品信息,一般不會變。
比如秒殺的商品信息,一般也不會變。
比如地圖的經緯度信息,一般也不會變。
用戶的關注列表,粉絲列表,消息列表等功能都可以用 Redis 的 List 結構來實現
Redis 可以非常方便的實現如共同關注、共同粉絲、共同喜好等功能(Set 類似與列表,但可自動排重的)
Redis不但提供了無需集合(Sets),還很體貼的提供了有序集合(Sorted Sets),因此,各種排行榜數據基本上都會使用Redis提供的Sorted Sets來實現
1.引入依賴(穩定版本)
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
2.注意應該導入下面包
如果存儲的是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.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.2redis-config.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="600" />
<property name="maxIdle" value="300" />
<property name="testOnBorrow" value="true" />
</bean>
<!-- 連接池配置,類似數據庫連接池 -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1"></property>
<property name="port" value="6379"></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 >
<bean id="redisUtil" class="com.mr.utils.RedisUtil">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
<!-- 下面這個是整合Mybatis的二級緩存使用的 -->
<!-- <bean id="redisCacheTransfer" class="cn.qlq.jedis.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>-->
</beans>
注意事項:
如果在多個spring配置文件中引入<context:property-placeholder …/>標籤,最後需要加上ignore-unresolvable=“true”,否則會報錯。
4.測試
packagecom.mr.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", "GZ", "廣州");
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
---------------
GZ - 廣州
BJ - 北京
SH - 上海
---------------
最後附加一個工具類RedisUtil.java
package com.mr.utils;
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
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("遞增因子必須大於0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 遞減
* @param key 鍵
* @param 要減少幾(小於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;
}
}
}
測試工具類
package com.mr.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);
}
}
結果:
測試工具類緩存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做緩存的時候最好是每個緩存的生命週期不固定,也就是分散的使緩存失效。可以設置有效期爲3-9小時。具體的做法就是在Java中產生一個3-9小時的隨機數。