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

示例存储库

GitHub spring-data-examples 存储库包含多个示例,您可以下载和使用这些示例来了解该库的工作原理。Spring中文文档

世界您好

首先,您需要设置正在运行的 Redis 服务器。 Spring Data Redis 需要 Redis 2.6 或更高版本,而 Spring Data Redis 集成了 LettuceJedis,这是两个流行的 Redis 开源 Java 库。Spring中文文档

现在,您可以创建一个简单的 Java 应用程序,用于存储和读取 Redis 的值。Spring中文文档

创建要运行的主应用程序,如以下示例所示:Spring中文文档

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

即使在这个简单的例子中,也有一些值得注意的事情需要指出:Spring中文文档

  • 您可以使用 .连接工厂是受支持驱动程序之上的抽象。RedisTemplateReactiveRedisTemplateRedisConnectionFactorySpring中文文档

  • 没有单一的使用 Redis 的方法,因为它支持广泛的数据结构,例如纯键(“字符串”)、列表、集合、排序集、流、哈希等。Spring中文文档