兩者之間的聯繫:
StringRedisTemplate和RedisTemplate都是spring框架下的reids操作工具,springboot項目使用時只需使用maven依賴包spring-boot-starter-data-redis即可,使用時將其註冊爲組件,如
@Autowired
StringRedisTemplate stringRedisTemplate;
//或者
//@Autowired
//RedisTemplate redisTemplate;
或者自己封裝一層類,並且用@Service等將其註冊爲組件
又或者手動裝載類,如
RedisTemplate<String,String> redisTemplate= (RedisTemplate)SpringContextUtil.getBean("redisTemplate",RedisTemplate.class);
另外,我們看StringRedisTemplate的源碼會發現,它繼承了RedisTemplate類,並對其序列化方式做了修改.
/**
* String-focused extension of RedisTemplate. Since most operations against Redis are String based, this class provides
* a dedicated class that minimizes configuration of its more generic {@link RedisTemplate template} especially in terms
* of serializers.
* <p/>
* Note that this template exposes the {@link RedisConnection} used by the {@link RedisCallback} as a
* {@link StringRedisConnection}.
*
* @author Costin Leau
*/
public class StringRedisTemplate extends RedisTemplate<String, String> {
/**
* Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
* and {@link #afterPropertiesSet()} still need to be called.
*/
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
}
/**
* Constructs a new <code>StringRedisTemplate</code> instance ready to be used.
*
* @param connectionFactory connection factory for creating new connections
*/
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
setConnectionFactory(connectionFactory);
afterPropertiesSet();
}
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
兩者之間的區別:
從上面的StringRedisTemplate的實現方式和RedisTemplate實現源碼中我們就能看出,兩者使用的序列化方式有所不同,一種是String的序列化策略(StringRedisTemplate),一種是默認的JDK的序列化策略(RedisTemplate)。StringRedisTemplate默認採用的是String的序列化策略,保存的key和value都是採用此策略序列化保存的。RedisTemplate默認採用的是JDK的序列化策略,保存的key和value都是採用此策略序列化保存的。
RedisTemplate使用的序列類在在操作數據的時候,比如說存入數據會將數據先序列化成字節數組然後在存入Redis數據庫,這個時候打開Redis查看的時候,你會看到你的數據不是以可讀的形式展現的,而是以字節數組顯示。當然從Redis獲取數據的時候也會默認將數據當做字節數組轉化,這樣就會導致一個問題,當需要獲取的數據不是以字節數組存在redis當中而是正常的可讀的字符串的時候,RedisTemplate就無法獲取導數據,這個時候獲取到的值就是NULL。這個時候StringRedisTempate就派上了用場。當Redis當中的數據值是以可讀的形式顯示出來的時候,只能使用StringRedisTemplate才能獲取到裏面的數據。所以當你使用RedisTemplate獲取不到數據的時候請檢查一下是不是Redis裏面的數據是可讀形式而非字節數組。
因此,當你的redis數據庫裏面本來存的是字符串數據或者你要存取的數據就是字符串類型數據的時候,那麼你就使用StringRedisTemplate即可,但是如果你的數據是複雜的對象類型,而取出的時候又不想做任何的數據轉換,直接從Redis裏面取出一個對象,那麼使用RedisTemplate是更好的選擇。
參考資料: