Support Classes

org.springframework.data.redis.support 提供各种可重用组件,这些组件依赖 Redis 作为后端存储。目前,该包包含各种基于 JDK 的接口实现(基于 Redis),例如 atomic 计数器和 JDK Collections

Package org.springframework.data.redis.support offers various reusable components that rely on Redis as a backing store. Currently, the package contains various JDK-based interface implementations on top of Redis, such as atomic counters and JDK Collections.

RedisList 向前兼容 Java 21 SequencedCollection

RedisList is forward-compatible with Java 21 SequencedCollection.

原子计数器可轻松封装 Redis 密钥递增,而集合则允许轻松管理 Redis 密钥,同时最大程度减少存储暴露或 API 泄漏。特别是,RedisSetRedisZSet 接口可轻松访问 Redis 支持的集合操作,例如 intersectionunionRedisList 在 Redis 之上实现了 ListQueueDeque 契约(及其同等的阻塞兄弟姐妹),将存储公开为 FIFO(先进先出)、LIFO(后进先出)或上限值为最少配置的集合。以下示例显示使用 RedisList 的 Bean 的配置:

The atomic counters make it easy to wrap Redis key incrementation while the collections allow easy management of Redis keys with minimal storage exposure or API leakage. In particular, the RedisSet and RedisZSet interfaces offer easy access to the set operations supported by Redis, such as intersection and union. RedisList implements the List, Queue, and Deque contracts (and their equivalent blocking siblings) on top of Redis, exposing the storage as a FIFO (First-In-First-Out), LIFO (Last-In-First-Out) or capped collection with minimal configuration. The following example shows the configuration for a bean that uses a RedisList:

  • Java

  • XML

@Configuration
class MyConfig {

  // …

  @Bean
  RedisList<String> stringRedisTemplate(RedisTemplate<String, String> redisTemplate) {
    return new DefaultRedisList<>(template, "queue-key");
  }
}
<?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="queue" class="org.springframework.data.redis.support.collections.DefaultRedisList">
    <constructor-arg ref="redisTemplate"/>
    <constructor-arg value="queue-key"/>
  </bean>

</beans>

以下示例展示 Deque 的 Java 配置示例:

The following example shows a Java configuration example for a Deque:

public class AnotherExample {

  // injected
  private Deque<String> queue;

  public void addTag(String tag) {
    queue.push(tag);
  }
}

如前面示例所示,使用代码从实际存储实现中分离出来。事实上,没有迹象表明 Redis 在下面使用。这使得从开发环境迁移到生产环境变得透明,并且极大地提高了可测试性(可将 Redis 实现替换为内存内实现)。

As shown in the preceding example, the consuming code is decoupled from the actual storage implementation. In fact, there is no indication that Redis is used underneath. This makes moving from development to production environments transparent and highly increases testability (the Redis implementation can be replaced with an in-memory one).