Redis @Reference在Spring Data Redis中不起作用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis @Reference在Spring Data Redis中不起作用相关的知识,希望对你有一定的参考价值。
我在@Reference
实施Spring Boot + Spring Data Redis
时遇到问题。 Address
是Employee
的列表,当我保存office
和home
地址时,我期待数据与Employee
一起保存。但数据没有得到保存,因此无法使用Address
搜索street
。
employee.Java
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("employees")
public class Employee {
@Id @Indexed
private String id;
private String firstName;
private String lastName;
@Reference
private List<Address> addresses;
}
address.Java
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("address")
public class Address {
@Id
private String id;
@Indexed
private String street;
private String city;
}
考试班
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EmployeeAdressTest extends RepositoryTestSupport{
@Autowired private EmployeeRepository employeeRepository;
@Before
public void setUp() throws JsonProcessingException {
Address home = Address.builder().street("ABC Street").city("Pune").build();
Address offc = Address.builder().street("XYZ Street").city("Pune").build();
Employee employee1 = Employee.builder().firstName("Raj").lastName("Kumar").addresses(Arrays.asList(home, offc)).build();
employeeRepository.save(employee1);
List<Employee> employees = employeeRepository.findByAddresses_Street("XYZ Street");
System.out.println("EMPLOYEE = "+employees);
}
@Test
public void test() {
}
}
Spring Doc:
8.8. Persisting References
Marking properties with @Reference allows storing a simple key reference instead of copying values into the hash itself. On loading from Redis, references are resolved automatically and mapped back into the object, as shown in the following example:
Example 30. Sample Property Reference
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
mother = people:a9d4b3a0-50d3-4538-a2fc-f7fc2581ee56
Reference stores the whole key (keyspace:id) of the referenced object.
?
答案
Spring Data Redis要求您将存储在home
和office
中的对象与引用对象employee1
分开保存。
这是(现在)在第8.8章末尾的官方文件中说明的:https://docs.spring.io/spring-data-redis/docs/current/reference/html/#redis.repositories.references
因此,如果您在保存home
之前将office
和employee1
保存到数据库中,那么您应该没问题。
对于稍后对引用对象所做的更新,相同的btw保持有效。仅保存引用对象不会保存引用对象的更新。
以上是关于Redis @Reference在Spring Data Redis中不起作用的主要内容,如果未能解决你的问题,请参考以下文章
Spring Session With Redis - HttpSession (Quick Start)
spring-boot redis:如何使用户的所有会话无效?