本站中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。
Getting Started
An easy way to bootstrap setting up a working environment is to create a Spring-based project via start.spring.io or create a Spring project in Spring Tools.
Example Repository
The GitHub spring-data-examples repository hosts several examples that you can download and play around with to get a feel for how the library works.
Hello World
First,you need to set up a running Redis server. Spring Data Redis requires Redis2.6 or above and Spring Data Redis integrates with Lettuce and jedis,two popular open-source Java libraries for Redis.
Now you can create a simple Java application that stores and reads a value to and from Redis.
Create the main application to run, as the following example shows:
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();
}
}
Even in this simple example,there are few notable things to point out:
- You can create an instance of
RedisTemplate(orReactiveRedisTemplatefor reactive usage ) with aRedisConnectionFactory.Connection factories are an abstraction on top of the supported drivers. - There’s no single way to use Redis as it comes with support for a wide range of data structures such as plain keys(“String”),list,sets,sorted sets,streams,hashes and so on.
Drivers
Connection Modes
Redis Template
Redis Cache
Redis Cluster
Hach Mapping
Pub/Sub Messaging
Redis Stream
Scripting
Redis Transactions
Pipelining
Support Classes