使用 RedisTemplate
處理物件
大部分使用者可能會使用 RedisTemplate
及其對應的套件 org.springframework.data.redis.core,或是其反應式變體 ReactiveRedisTemplate
。實際上,由於其豐富的功能集,Template 是 Redis 模組的核心類別。Template 為 Redis 互動提供高階抽象化。雖然 [Reactive]RedisConnection 提供接受和傳回二進位值(位元組陣列)的低階方法,但 Template 負責處理序列化和連線管理,讓使用者無需處理這些細節。
RedisTemplate
類別實作 RedisOperations
介面,其反應式變體 ReactiveRedisTemplate
則實作 ReactiveRedisOperations
。
參考 [Reactive]RedisTemplate 實例上的操作,偏好的方式是透過 [Reactive]RedisOperations 介面。 |
此外,Template 提供操作視圖(遵循 Redis 命令參考中的分組),這些視圖提供豐富、泛型化的介面,用於針對特定類型或特定鍵(透過 KeyBound 介面)進行操作,如下表所述
操作視圖
-
命令式
-
反應式
介面 | 描述 |
---|---|
鍵類型操作 |
|
Redis 地理空間操作,例如 |
|
Redis 雜湊操作 |
|
Redis HyperLogLog 操作,例如 |
|
Redis 列表操作 |
|
Redis 集合操作 |
|
Redis 字串(或值)操作 |
|
Redis zset(或排序集合)操作 |
|
鍵綁定操作 |
|
Redis 鍵綁定地理空間操作 |
|
Redis 雜湊鍵綁定操作 |
|
Redis 鍵綁定操作 |
|
Redis 列表鍵綁定操作 |
|
Redis 集合鍵綁定操作 |
|
Redis 字串(或值)鍵綁定操作 |
|
Redis zset(或排序集合)鍵綁定操作 |
介面 | 描述 |
---|---|
鍵類型操作 |
|
Redis 地理空間操作,例如 |
|
Redis 雜湊操作 |
|
Redis HyperLogLog 操作,例如( |
|
Redis 列表操作 |
|
Redis 集合操作 |
|
Redis 字串(或值)操作 |
|
Redis zset(或排序集合)操作 |
一旦設定完成,Template 就是執行緒安全的,並且可以在多個實例中重複使用。
RedisTemplate 對於其大部分操作使用基於 Java 的序列化器。這表示由 Template 寫入或讀取的任何物件都會透過 Java 進行序列化和反序列化。
您可以變更 Template 上的序列化機制,Redis 模組提供了幾種實作,這些實作在 org.springframework.data.redis.serializer 套件中提供。請參閱 Serializers 以取得更多資訊。您也可以將任何序列化器設定為 null,並透過將 enableDefaultSerializer 屬性設定為 false,將 RedisTemplate 與原始位元組陣列一起使用。請注意,Template 要求所有鍵都不能為 null。但是,只要底層序列化器接受,值就可以為 null。請閱讀每個序列化器的 Javadoc 以取得更多資訊。
對於您需要特定 Template 視圖的情況,請將該視圖宣告為依賴項並注入 Template。容器會自動執行轉換,消除 opsFor[X] 呼叫,如下列範例所示
-
Java 命令式
-
Java 反應式
-
XML
@Configuration
class MyConfig {
@Bean
LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}
@Configuration
class MyConfig {
@Bean
LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
ReactiveRedisTemplate<String, String> ReactiveRedisTemplate(ReactoveRedisConnectionFactory connectionFactory) {
return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="redisConnectionFactory"/>
...
</beans>
-
命令式
-
反應式
public class Example {
// inject the actual operations
@Autowired
private RedisOperations<String, String> operations;
// inject the template as ListOperations
@Resource(name="redisTemplate")
private ListOperations<String, String> listOps;
public void addLink(String userId, URL url) {
listOps.leftPush(userId, url.toExternalForm());
}
}
public class Example {
// inject the actual template
@Autowired
private ReactiveRedisOperations<String, String> operations;
public Mono<Long> addLink(String userId, URL url) {
return operations.opsForList().leftPush(userId, url.toExternalForm());
}
}
專注於字串的便利類別
由於儲存在 Redis 中的鍵和值通常是 java.lang.String,Redis 模組為 RedisConnection 和 RedisTemplate 提供了兩個擴充功能,分別是 StringRedisConnection(及其 DefaultStringRedisConnection 實作)和 StringRedisTemplate,作為密集字串操作的便利一站式解決方案。除了綁定到字串鍵之外,Template 和連線在底層使用 StringRedisSerializer,這表示儲存的鍵和值是人類可讀的(假設在 Redis 和您的程式碼中都使用相同的編碼)。以下列表顯示了一個範例
-
Java 命令式
-
Java 反應式
-
XML
@Configuration
class RedisConfiguration {
@Bean
LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
@Configuration
class RedisConfiguration {
@Bean
LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
ReactiveStringRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
return new ReactiveStringRedisTemplate<>(factory);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="redisConnectionFactory"/>
</beans>
-
命令式
-
反應式
public class Example {
@Autowired
private StringRedisTemplate redisTemplate;
public void addLink(String userId, URL url) {
redisTemplate.opsForList().leftPush(userId, url.toExternalForm());
}
}
public class Example {
@Autowired
private ReactiveStringRedisTemplate redisTemplate;
public Mono<Long> addLink(String userId, URL url) {
return redisTemplate.opsForList().leftPush(userId, url.toExternalForm());
}
}
與其他 Spring Template 一樣,RedisTemplate 和 StringRedisTemplate 讓您透過 RedisCallback 介面直接與 Redis 通訊。此功能讓您完全控制,因為它直接與 RedisConnection 通訊。請注意,當使用 StringRedisTemplate 時,回呼會收到 StringRedisConnection 的實例。以下範例顯示如何使用 RedisCallback 介面
public void useCallback() {
redisOperations.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
Long size = connection.dbSize();
// Can cast to StringRedisConnection if using a StringRedisTemplate
((StringRedisConnection)connection).set("key", "value");
}
});
}
序列化器
從框架的角度來看,儲存在 Redis 中的資料只是位元組。雖然 Redis 本身支援各種型別,但在大多數情況下,這些型別指的是資料的儲存方式,而不是它代表的內容。資訊是否轉換為字串或任何其他物件,取決於使用者決定。
在 Spring Data 中,使用者(自訂)型別和原始資料(反之亦然)之間的轉換由 Spring Data Redis 在 org.springframework.data.redis.serializer 套件中處理。
此套件包含兩種型別的序列化器,顧名思義,它們負責處理序列化過程
-
基於
RedisSerializer
的雙向序列化器。 -
使用
RedisElementReader
和RedisElementWriter
的元素讀取器和寫入器。
這些變體之間的主要區別在於 RedisSerializer
主要序列化為 byte[]
,而讀取器和寫入器則使用 ByteBuffer
。
有多種實作可用(包括本文檔中已提及的兩種)
-
JdkSerializationRedisSerializer
,預設用於RedisCache
和RedisTemplate
。 -
StringRedisSerializer。
然而,可以透過 Spring OXM 支援使用 OxmSerializer
進行物件/XML 映射,或使用 Jackson2JsonRedisSerializer
或 GenericJackson2JsonRedisSerializer
以 JSON 格式儲存資料。
請注意,儲存格式不僅限於值。它可以毫無限制地用於鍵、值或雜湊。
預設情況下, 如果您擔心 Java 序列化造成的安全漏洞,請考慮核心 JVM 層級的通用序列化篩選機制 |