开始使用
一个简单的引导设置工作环境的方法是通过 start.spring.io 创建一个基于 Spring 的项目,或者在 Spring Tools 中创建一个 Spring 项目。
示例仓库
GitHub 上的 spring-data-examples 仓库 提供了多个示例,你可以下载并尝试运行这些示例,以便更好地了解该库的工作原理。
你好世界
现在你可以创建一个简单的 Java 应用程序,用于将值存储到 Redis 并从 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 并没有单一的方式,因为它支持多种数据结构,例如普通键("字符串")、列表、集合、有序集合、流、哈希等。