在說到StringRedisTemplate操作Redis數據的時候,我們順便談談StringRedisTemplate和RedisTemplate的區別。
一、StringRedisTemplate和RedisTemplate的區別
區別如下:
1.兩者關系是StringRedisTemplate繼承RedisTemplate。
從StringRedisTemplate源碼即可看出,如下圖所示:
2.兩者的數據是不共通的,也就是說StringRedisTemplate只能管理StringRedisTemplate里面的數據,RedisTemplate只能管理RedisTemplate中的數據。
3.使用的序列化類不同。
使用的序列化哪里不同?如下所示:
(1)RedisTemplate使用的是JdkSerializationRedisSerializer 存入數據會將數據先序列化成字節組然后再存入Redis數據庫。
(2)StringRedisTemplate使用的是StringRedisSerializer。
使用時注意事項:
(1)當你的Redis數據庫里面本來存的是字符串數據或者是你要存取的數據就是字符串類型數據的時候,那么你就使用StringRedisTemplate即可;
(2)但是如果你的數據是復雜的對象類型,而取出的時候又不想做任何數據轉換,直接從Redis里面取出一個對象,那么使用RedisTemplate是更好的選擇;
(3)RedisTemplate中存取數據都是字節數組。當Redis職工存入的數據是可讀形式而非字節數組時,使用RedisTemplate取值的時候會無法獲取導出數據,獲得的值為null。可以使用StringRedisTemplate試試;
二、RedisTemplate定義了5種數據結構操作
redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set redisTemplate.opsForZSet();//操作有序set
三、StringRedisTemplate常用操作
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入數據和設置緩存時間 stringRedisTemplate.boundValueOps("test").increment(-1);//val做-1操作 stringRedisTemplate.opsForValue().get("test")//根據key獲取緩存中的val stringRedisTemplate.boundValueOps("test").increment(1);//val +1 stringRedisTemplate.getExpire("test")//根據key獲取過期時間 stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根據key獲取過期時間並換算成指定單位 stringRedisTemplate.delete("test");//根據key刪除緩存 stringRedisTemplate.hasKey("546545");//檢查key是否存在,返回boolean值 stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合 stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//設置過期時間 stringRedisTemplate.opsForSet().isMember("red_123", "1")//根據key查看集合中是否存在指定數據 stringRedisTemplate.opsForSet().members("red_123");//根據key獲取set集合
單測示例:
package cn.test; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import com.blog.springboot.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PracticeJunitTest { @Autowired private StringRedisTemplate stringRedisTemplate; @Test public void testConnectionRedis() throws Exception { stringRedisTemplate.opsForValue().set("youcong", "ok"); System.out.println(stringRedisTemplate.opsForValue().get("youcong")); } }
參考鏈接如下:
StringRedisTemplate操作redis數據