1. 程式人生 > 資料庫 >RedisTemplate操作Redis

RedisTemplate操作Redis

一、SpringDataRedis簡介

1、Redis

redis是一款開源的Key-Value資料庫,執行在記憶體中,由C語言編寫。企業開發通常採用Redis來實現快取。同類的產品還有memcache 、memcached 等。

2、Jedis

Jedis是Redis官方推出的一款面向Java的客戶端,提供了很多介面供Java語言呼叫。可以在Redis官網下載,當然還有一些開源愛好者提供的客戶端,如Jredis、SRP等等,推薦使用Jedis。

3、Spring Data Redis

Spring-data-redis是spring大家族的一部分,提供了在srping應用中通過簡單的配置訪問redis服務,對reids底層開發包(Jedis, JRedis, and RJC)進行了高度封裝,RedisTemplate提供了redis各種操作、異常處理及序列化,支援釋出訂閱,並對spring 3.1 cache進行了實現。

spring-data-redis針對jedis提供瞭如下功能:

  1. 連線池自動管理,提供了一個高度封裝的“RedisTemplate”類
  2. 針對jedis客戶端中大量api進行了歸類封裝,將同一型別操作封裝為operation介面
  • ValueOperations:簡單K-V操作
  • SetOperations:set型別資料操作
  • ZSetOperations:zset型別資料操作
  • HashOperations:針對map型別的資料操作
  • ListOperations:針對list型別的資料操作
  1. 提供了對key的“bound”(繫結)便捷化操作API,可以通過bound封裝指定的key,然後進行一系列的操作而無須“顯式”的再次指定Key,即BoundKeyOperations:
  • BoundValueOperations
  • BoundSetOperations
  • BoundListOperations
  • BoundSetOperations
  • BoundHashOperations
  1. 將事務操作封裝,有容器控制。
  2. 針對資料的“序列化/反序列化”,提供了多種可選擇策略(RedisSerializer)

JdkSerializationRedisSerializer:POJO物件的存取場景,使用JDK本身序列化機制,將pojo類通過ObjectInputStream/ObjectOutputStream進行序列化操作,最終redis-server中將儲存位元組序列。是目前最常用的序列化策略。

StringRedisSerializer:Key或者value為字串的場景,根據指定的charset對資料的位元組序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。

JacksonJsonRedisSerializer:jackson-json工具提供了javabean與json之間的轉換能力,可以將pojo例項序列化成json格式儲存在redis中,也可以將json格式的資料轉換成pojo例項。因為jackson工具在序列化和反序列化時,需要明確指定Class型別,因此此策略封裝起來稍微複雜。【需要jackson-mapper-asl工具支援】

二、RedisTemplate中API使用

1、pom.xml依賴

<!--Redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、配置檔案

# Redis伺服器連線埠
spring.redis.port=6379
# Redis伺服器地址
spring.redis.host=127.0.0.1
# Redis資料庫索引(預設為0)
spring.redis.database=0
# Redis伺服器連線密碼(預設為空)
spring.redis.password=
# 連線池最大連線數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=8
# 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 連線池中的最大空閒連線
spring.redis.jedis.pool.max-idle=8
# 連線池中的最小空閒連線
spring.redis.jedis.pool.min-idle=0
# 連線超時時間(毫秒)
spring.redis.timeout=5000ms

3、RedisTemplate的直接方法 

//首先使用@Autowired注入RedisTemplate(後面直接使用,就不特殊說明)
@Autowired
private RedisTemplate redisTemplate;

//刪除單個key
public void delete(String key){
    redisTemplate.delete(key);
}

//刪除多個key
public void deleteKey (String ...keys){
    redisTemplate.delete(keys);
}

//指定key的失效時間
public void expire(String key,long time){
    redisTemplate.expire(key,time,TimeUnit.MINUTES);
}

//根據key獲取過期時間
public long getExpire(String key){
    Long expire = redisTemplate.getExpire(key);
    return expire;
}

//判斷key是否存在
public boolean hasKey(String key){
    return redisTemplate.hasKey(key);
}

4、String型別相關操作 

//1)、新增快取

//通過redisTemplate設定值
redisTemplate.boundValueOps("StringKey").set("StringValue");
redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);

//通過BoundValueOperations設定值
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.MINUTES);

//通過ValueOperations設定值
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);


//2)、設定過期時間(單獨設定)
redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);


//3)、獲取快取值

//通過redisTemplate設定值
String str1 = (String) redisTemplate.boundValueOps("StringKey").get();

//通過BoundValueOperations獲取值
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();

//通過ValueOperations獲取值
ValueOperations ops = redisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");


//4)、刪除key
Boolean result = redisTemplate.delete("StringKey");


//5)、順序遞增
redisTemplate.boundValueOps("StringKey").increment(3L);


//6)、順序遞減
redisTemplate.boundValueOps("StringKey").increment(-3L);

5、Hash型別相關操作

//1)、新增快取

//通過redisTemplate設定值
redisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");

//通過BoundValueOperations設定值
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");

//通過ValueOperations設定值
HashOperations hashOps = redisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");


//2)、設定過期時間(單獨設定)
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);


//3)、新增一個Map集合
HashMap<String, String> hashMap = new HashMap<>();
redisTemplate.boundHashOps("HashKey").putAll(hashMap );


//4)、設定過期時間(單獨設定)
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);


//5)、提取所有的小key

//通過redisTemplate獲取值
Set keys1 = redisTemplate.boundHashOps("HashKey").keys();

//通過BoundValueOperations獲取值
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();

//通過ValueOperations獲取值
HashOperations hashOps = redisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");


//6)、提取所有的value值

//通過redisTemplate獲取值
List values1 = redisTemplate.boundHashOps("HashKey").values();

//通過BoundValueOperations獲取值
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
List values2 = hashKey.values();

//通過ValueOperations獲取值
HashOperations hashOps = redisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");


//7)、根據key提取value值

//通過redisTemplate獲取
String value1 = (String) redisTemplate.boundHashOps("HashKey").get("SmallKey");

//通過BoundValueOperations獲取值
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
String value2 = (String) hashKey.get("SmallKey");

//通過ValueOperations獲取值
HashOperations hashOps = redisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");


//8)、獲取所有的鍵值對集合

//通過redisTemplate獲取
Map entries = redisTemplate.boundHashOps("HashKey").entries();

//通過BoundValueOperations獲取值
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Map entries1 = hashKey.entries();

//通過ValueOperations獲取值
HashOperations hashOps = redisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");


//9)、刪除

//刪除小key
redisTemplate.boundHashOps("HashKey").delete("SmallKey");

//刪除大key
redisTemplate.delete("HashKey");


//10)、判斷Hash中是否含有該值
Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");

6、Set型別相關操作

//1)、新增Set快取(值可以是一個,也可是多個)

//通過redisTemplate設定值
redisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");

//通過BoundValueOperations設定值
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");

//通過ValueOperations設定值
SetOperations setOps = redisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");


//2)、設定過期時間(單獨設定)
redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("setKey",1,TimeUnit.MINUTES);


//3)、根據key獲取Set中的所有值

//通過redisTemplate獲取值
Set set1 = redisTemplate.boundSetOps("setKey").members();

//通過BoundValueOperations獲取值
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
Set set2 = setKey.members();

//通過ValueOperations獲取值
SetOperations setOps = redisTemplate.opsForSet();
Set set3 = setOps.members("setKey");


//4)、根據value從一個set中查詢,是否存在
Boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");


//5)、獲取Set快取的長度
Long size = redisTemplate.boundSetOps("setKey").size();


//6)、移除指定的元素
Long result1 = redisTemplate.boundSetOps("setKey").remove("setValue1");


//7)、移除指定的key
Boolean result2 = redisTemplate.delete("setKey");

7、 List型別相關操作

//1)、新增快取

//1-1、通過redisTemplate設定值
redisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
redisTemplate.boundListOps("listKey").rightPush("listRightValue2");

//通過BoundValueOperations設定值
BoundListOperations listKey = redisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");

//通過ValueOperations設定值
ListOperations opsList = redisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");


//2)、將List放入快取
ArrayList<String> list = new ArrayList<>();
redisTemplate.boundListOps("listKey").rightPushAll(list);
redisTemplate.boundListOps("listKey").leftPushAll(list);


//3)、設定過期時間(單獨設定)
redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("listKey",1,TimeUnit.MINUTES);


//4)、獲取List快取全部內容(起始索引,結束索引)
List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10); 


//5)、從左或從右彈出一個元素

//從左側彈出一個元素
String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop(); 

//從右側彈出一個元素 
String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); 


//6)、根據索引查詢元素
String listKey4 = (String) redisTemplate.boundListOps("listKey").index(1);


//7)、獲取List快取的長度
Long size = redisTemplate.boundListOps("listKey").size();


//8)、根據索引修改List中的某條資料(key,索引,值)
redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");


//9)、移除N個值為value(key,移除個數,值)
redisTemplate.boundListOps("listKey").remove(3L,"value");

8、Zset型別的相關操作 

//1)、向集合中插入元素,並設定值

//通過redisTemplate設定值
redisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);

//通過BoundValueOperations設定值
BoundZSetOperations zSetKey = redisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);

//通過ValueOperations設定值
ZSetOperations zSetOps = redisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);


//2)、向集合中插入多個元素,並設定分數
DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("zSetVaule1", 2.1D);
DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("zSetVaule2", 3.3D);
redisTemplate.boundZSetOps("zSetKey").add(new HashSet<>(Arrays.asList(p1,p2)));


//3)、按照排名先後(從小到大)列印指定區間內的元素, -1為列印全部
Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(key, 0, -1);


//4)、獲得指定元素的分數
Double score = redisTemplate.boundZSetOps("zSetKey").score("zSetVaule");


//5)、返回集合內的成員個數
Long size = redisTemplate.boundZSetOps("zSetKey").size();


//6)、返回集合內指定分數範圍的成員個數(Double型別)
Long COUNT = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);


//7)、返回集合內元素在指定分數範圍內的排名(從小到大)
Set byScore = redisTemplate.boundZSetOps("zSetKey").rangeByScore(0D, 2.2D);


//8)、帶偏移量和個數,(key,起始分數,最大分數,偏移量,個數)
Set<String> ranking2 = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);


//9)、返回集合內元素的排名,以及分數(從小到大)
Set<TypedTuple<String>> tuples = redisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
for (TypedTuple<String> tuple : tuples) {
    System.out.println(tuple.getValue() + " : " + tuple.getScore());
}


//10)、返回指定成員的排名

//從小到大
Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");

//從大到小
Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");


//11)、從集合中刪除指定元素
redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");


//12)、刪除指定索引範圍的元素(Long型別)
redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);


//13)、刪除指定分數範圍內的元素(Double型別)
redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);


//14)、為指定元素加分(Double型別)
Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);