|
对于最新的稳定版本,请使用 Spring Data Redis 4.0.4! |
快速开始
一种快速搭建工作环境的简便方法是通过 start.spring.io 创建一个基于 Spring 的项目,或在 Spring Tools 中创建一个 Spring 项目。
示例仓库
GitHub 上的 spring-data-examples 仓库 提供了多个示例,您可以下载并试用这些示例,以了解该库的工作方式。
你好,世界
首先,你需要设置一个正在运行的 Redis 服务器。 Spring Data Redis 要求 Redis 2.6 或更高版本,并且 Spring Data Redis 集成了 Lettuce 和 Jedis,这两个是 Redis 常用的开源 Java 客户端库。
现在,你可以创建一个简单的 Java 应用程序,用于向 Redis 存储和读取值。
创建要运行的主应用程序,如下例所示:
-
Imperative
-
Reactive
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisApplication {
private static final Log LOG = LogFactory.getLog(RedisApplication.class);
public static void main(String[] args) {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
connectionFactory.afterPropertiesSet();
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setDefaultSerializer(StringRedisSerializer.UTF_8);
template.afterPropertiesSet();
template.opsForValue().set("foo", "bar");
LOG.info("Value at foo:" + template.opsForValue().get("foo"));
connectionFactory.destroy();
}
}
import reactor.core.publisher.Mono;
import java.time.Duration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
public class ReactiveRedisApplication {
private static final Log LOG = LogFactory.getLog(ReactiveRedisApplication.class);
public static void main(String[] args) {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
connectionFactory.afterPropertiesSet();
ReactiveRedisTemplate<String, String> template = new ReactiveRedisTemplate<>(connectionFactory,
RedisSerializationContext.string());
Mono<Boolean> set = template.opsForValue().set("foo", "bar");
set.block(Duration.ofSeconds(10));
LOG.info("Value at foo:" + template.opsForValue().get("foo").block(Duration.ofSeconds(10)));
connectionFactory.destroy();
}
}
即使在这个简单的示例中,也有几点值得注意的地方:
-
您可以使用
RedisConnectionFactory创建RedisTemplate(或用于响应式场景的ReactiveRedisTemplate)的实例。连接工厂是对所支持驱动程序的抽象层。 -
使用 Redis 并没有唯一的方式,因为它支持多种数据结构,例如普通键(“字符串”)、列表、集合、有序集合、流、哈希等。