我正在使用Spring Data Redis
开发Spring Boot
示例。在此示例中,我希望将所有键和值存储为json格式。使用CrudRepository
模式执行CRUD
操作。我是否需要为密钥存储为JSON设置任何配置?我浏览了链接:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/,但不清楚在哪里设置配置。
127.0.0.1:6379> SMEMBERS user:2be0135f-dbda-490c-8cf9-cd9a7bfdce1b:idx
1) "user:firstName:John"
2) "user:lastName:Kerr"
3) "user:role.roleName:API"
4) "user:middleName:Lima"
127.0.0.1:6379> HGETALL user:2be0135f-dbda-490c-8cf9-cd9a7bfdce1b
1) "_class"
2) "com.baeldung.spring.data.redis.model.User"
3) "id"
4) "2be0135f-dbda-490c-8cf9-cd9a7bfdce1b"
5) "firstName"
6) "John"
7) "middleName"
8) "Lima"
9) "lastName"
10) "Kerr"
11) "role.id"
12) "R2"
13) "role.roleName"
14) "API"
127.0.0.1:6379>
Role.java
@RedisHash("Role")
public class Role {
private @Id String id;
private @Indexed String roleName;
}
User.java
@RedisHash("user")
public class User {
private @Id String id;
private @Indexed String firstName;
private @Indexed String middleName;
private @Indexed String lastName;
private Role role;
}
RedisConfig.java
@Configuration
@ConfigurationProperties
@EnableRedisRepositories("com.baeldung.spring.data.redis.repository")
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
final RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class));
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
return template;
}
}
MainApp.java
@SpringBootApplication
@Transactional
public class MainAppDemo implements CommandLineRunner{
RedisMappingContext mappingContext = new RedisMappingContext();
ExampleQueryMapper mapper = new ExampleQueryMapper(mappingContext, new PathIndexResolver(mappingContext));
@Autowired private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(MainAppDemo.class, args);
}
@Override
public void run(String... args) throws Exception {
Role role1 = Role.builder().id("R1").roleName("ADMIN").build();
User user1 = User.builder().firstName("Matt").middleName("Mike").lastName("Wixson").role(role1).build();
Role role2 = Role.builder().id("R2").roleName("API").build();
User user2 = User.builder().firstName("John").middleName("Lima").lastName("Kerr").role(role2).build();
userRepository.save(user1);
userRepository.save(user2);
}
}