开始
引导设置工作环境的一种简单方法是通过 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();
	}
}
即使在这个简单的示例中,也有一些值得注意的事情需要指出:
- 
您可以创建
RedisTemplate(或ReactiveRedisTemplate用于反应式用法),并使用RedisConnectionFactory.连接工厂是支持的驱动程序之上的抽象。 - 
使用 Redis 的方法并不单一,因为它支持各种数据结构,例如纯键(“字符串”)、列表、集合、排序集、流、哈希等。