Introduction to Spring Data Redis – Spring Data Redis简介

最后修改: 2016年 2月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial is an introduction to Spring Data Redis, which provides the abstractions of the Spring Data platform to Redis — the popular in-memory data structure store.

本教程是对Spring Data Redis的介绍,它为Redis–流行的内存数据结构存储提供了Spring Data平台的抽象。

Redis is driven by a keystore-based data structure to persist data and can be used as a database, cache, message broker, etc.

Redis由一个基于keystore的数据结构驱动,用于持久化数据,可以作为数据库、缓存、消息代理等使用。

We’ll be able to use the common patterns of Spring Data (templates, etc.) while also having the traditional simplicity of all Spring Data projects.

我们将能够使用Spring Data的常见模式(模板等),同时也有所有Spring Data项目的传统简单性。

2. Maven Dependencies

2.Maven的依赖性

Let’s start by declaring the Spring Data Redis dependencies in the pom.xml:

让我们先在pom.xml中声明Spring Data Redis的依赖关系。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.3.3.RELEASE</version>
 </dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
    <type>jar</type>
</dependency>

The latest versions of spring-data-redis and jedis can be downloaded from Maven Central.

spring-data-redisjedis的最新版本可以从Maven中心下载。

Alternatively, we can use the Spring Boot starter for Redis, which will eliminate the need for separate spring-data and jedis dependencies:

另外,我们可以使用Redis的Spring Boot启动器,这样就不需要单独的spring-datajedis依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.7.2</version>
</dependency>

Again, Maven Central offers the latest version information.

同样,Maven Central提供最新的版本信息。

3. The Redis Configuration

3.Redis的配置

To define the connection settings between the application client and the Redis server instance, we need to use a Redis client.

为了定义应用程序客户端和Redis服务器实例之间的连接设置,我们需要使用一个Redis客户端。

There is a number of Redis client implementations available for Java. In this tutorial, we’ll use Jedis — a simple and powerful Redis client implementation.

有许多可用于 Java 的 Redis 客户端实现。在本教程中,我们将使用Jedis – 一个简单而强大的 Redis 客户端实现。

There is good support for both XML and Java configuration in the framework. For this tutorial, we’ll use Java-based configuration.

该框架对XML和Java配置都有良好的支持。在本教程中,我们将使用基于Java的配置。

3.1. Java Configuration

3.1. Java配置

Let’s start with the configuration bean definitions:

让我们从配置Bean的定义开始:

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    return new JedisConnectionFactory();
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}

The configuration is quite simple.

配置相当简单。

First, using the Jedis client, we’re defining a connectionFactory.

首先,使用Jedis客户端,我们要定义一个connectionFactory

Then we defined a RedisTemplate using the jedisConnectionFactory. This can be used for querying data with a custom repository.

然后我们使用jedisConnectionFactory定义了一个RedisTemplate。这可用于用自定义存储库查询数据。

3.2. Custom Connection Properties

3.2.自定义连接属性

Notice that the usual connection-related properties are missing in the above configuration. For example, the server address and port are missing in the configuration. The reason is simple: we’re using the defaults.

请注意,在上述配置中缺少与连接有关的常规属性。例如,配置中缺少服务器地址和端口。原因很简单:我们使用的是默认值。

However, if we need to configure the connection details, we can always modify the jedisConnectionFactory configuration:

然而,如果我们需要配置连接细节,我们可以随时修改jedisConnectionFactory配置。

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory jedisConFactory
      = new JedisConnectionFactory();
    jedisConFactory.setHostName("localhost");
    jedisConFactory.setPort(6379);
    return jedisConFactory;
}

4. Redis Repository

4.Redis存储库

Let’s use a Student entity:

让我们使用一个Student实体。

@RedisHash("Student")
public class Student implements Serializable {
  
    public enum Gender { 
        MALE, FEMALE
    }

    private String id;
    private String name;
    private Gender gender;
    private int grade;
    // ...
}

4.1. The Spring Data Repository

4.1.Spring Data Repository

Let’s now create the StudentRepository:

现在我们来创建StudentRepository

@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}

5. Data Access Using StudentRepository

5.使用StudentRepository的数据访问

By extending CrudRepository in StudentRepository, we automatically get a complete set of persistence methods that perform CRUD functionality.

通过在StudentRepository中扩展CrudRepository,我们自动获得一套完整的持久化方法,执行CRUD功能。

5.1. Saving a New Student Object

5.1.保存一个新的学生对象

Let’s save a new student object in the data store:

让我们在数据存储中保存一个新的学生对象。

Student student = new Student(
  "Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);

5.2. Retrieving an Existing Student Object

5.2.检索一个现有的学生对象

We can verify the correct insertion of the student in the previous section by fetching the student data:

我们可以通过获取学生数据来验证上一节中学生的插入是否正确。

Student retrievedStudent = 
  studentRepository.findById("Eng2015001").get();

5.3. Updating an Existing Student Object

5.3.更新一个现有的学生对象

Let’s change the name of the student retrieved above and save it again:

让我们改变上面检索到的学生的名字,并再次保存它。

retrievedStudent.setName("Richard Watson");
studentRepository.save(student);

Finally, we can retrieve the student’s data again and verify that the name is updated in the data store.

最后,我们可以再次检索学生的数据,并验证数据存储中的名字是否已经更新。

5.4. Deleting Existing Student Data

5.4.删除现有的学生数据

We can delete the inserted student data:

我们可以删除插入的学生数据。

studentRepository.deleteById(student.getId());

Now we can search for the student object and verify that the result is null.

现在我们可以搜索学生对象并验证其结果是否为null

5.5. Find All Student Data

5.5.查找所有学生数据

We can insert a few student objects:

我们可以插入一些学生对象。

Student engStudent = new Student(
  "Eng2015001", "John Doe", Student.Gender.MALE, 1);
Student medStudent = new Student(
  "Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.save(engStudent);
studentRepository.save(medStudent);

We can also achieve this by inserting a collection. For that, there is a different method — saveAll() — that accepts a single Iterable object containing multiple student objects that we want to persist.

我们也可以通过插入一个集合来实现这一点。为此,有一个不同的方法–saveAll()–接受一个单一的Iterable对象,该对象包含我们想要持久化的多个学生对象。

To find all inserted students, we can use the findAll() method:

要找到所有插入的学生,我们可以使用findAll()方法。

List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);

Then we can quickly check the size of the students list or verify for a greater granularity by checking the properties of each object.

然后我们可以快速检查学生的大小。Georgia, ‘Times New Roman’, ‘Bitstream Charter’, Times, serif;line-height: 1.5″>学生名单 或者通过检查每个对象的属性来验证更大的粒度。

6. Conclusion

6.结论

In this article, we went through the basics of Spring Data Redis.

在这篇文章中,我们了解了Spring Data Redis的基础知识。

The source code of the examples above can be found in the GitHub project.

上述例子的源代码可以在GitHub项目中找到。