跳到主要内容

开始使用

DeepSeek V3 中英对照 Getting Started

一个简单的引导设置工作环境的方法是通过 start.spring.io 创建一个基于 Spring 的项目,或者在 Spring Tools 中创建一个 Spring 项目。

示例仓库

GitHub 上的 spring-data-examples 仓库 提供了多个示例,你可以下载并尝试运行这些示例,以便更好地了解该库的工作原理。

你好世界

首先,你需要设置一个正在运行的 Redis 服务器。Spring Data Redis 要求 Redis 2.6 及以上版本,并且 Spring Data Redis 集成了 LettuceJedis,这是两个流行的开源 Java Redis 库。

现在你可以创建一个简单的 Java 应用程序,用于将值存储到 Redis 并从 Redis 中读取该值。

创建主应用程序来运行,如下例所示:

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();
}
}
java

在这个简单的示例中,有几点值得注意的地方:

  • 你可以使用 RedisConnectionFactory 创建一个 RedisTemplate(或者对于响应式用法,使用 ReactiveRedisTemplate)的实例。连接工厂是对支持的驱动程序的抽象。

  • 使用 Redis 并没有单一的方式,因为它支持多种数据结构,例如普通键("字符串")、列表、集合、有序集合、流、哈希等。