我希望使用Spring从 Redis 中保存和获取数据。Redis只有一个名为SOME
的配置文件。我成功地保存了数据,但是当我尝试使用findByIdAndName
方法获取数据时,我总是得到一个空的可选对象。
我的POJO如下:
@RedisHash("Some")
@Data
@AllArgsConstructor
public class SomeInfo implements Serializable {
@Id
private String id;
@Indexed
private String name;
@TimeToLive(unit = TimeUnit.DAYS)
private Long expiration;
}
我的代码仓库:
public interface SomeInfoRepository extends CrudRepository<SomeInfo, String> {
Optional<SomeInfo> findByIdAndName(String id, String name);
}
我有一份Redis配置:
@Profile(Profiles.SOME)
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RedisProperties.class)
@EnableRedisRepositories(basePackageClasses = { SomeInfoRepository.class })
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(ObjectMapper objectMapper, RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
return template;
}
@Bean(name = "someTopic")
public ChannelTopic someTopic(@Value("${app.topics.some}") String someChannel) {
return new ChannelTopic(someChannel);
}
@Bean
public RedisMessageListenerContainer roundRedisContainer(RedisConnectionFactory connectionFactory,
SomeMessageListener someMessageListener,
@Qualifier("someTopic") ChannelTopic someTopic) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(someMessageListener, someTopic);
return container;
}
}
以及 application.yml
spring:
redis:
host: localhost
port: 6379
ssl: false
password: some
data.redis.repositories.enabled: false
我知道数据已经保存好了:
keys *
1) "Some:36:idx"
2) "Some"
3) "Some:name:af0b83a2b15f018bdd404aef33bfb11f"
4) "Some:name:f5f8c3a9119bb822b0c2fde3265d37fa"
5) "Some:41:idx"
6) "Some:41:phantom"
7) "Some:36:phantom"
8) "Some:41"
9) "Some:36"
并且
hgetall Some:41
1) "_class"
2) "ru.some.SomeInfo"
3) "id"
4) "41"
5) "name"
6) "af0b83a2b15f018bdd404aef33bfb11f"
7) "expiration"
8) "30"
那么,为什么我的方法
findByIdAndName
不起作用呢?
如果我使用方法 findById(id)
,它可以正确地工作并返回数据。
findByIdAndName
时是否执行了任何GET操作以及执行了哪个键。但是不要在生产系统上长时间运行redis monitor。 - nimbudew"SINTER" "Some:id:41" "Some:name:af0b83a2b15f018bdd404aef33bfb11f"
。 - AnnKont> SINTER Some:id:41
并得到:(空列表或集合)
执行以下命令:> SINTER Some:name:af0b83a2b15f018bdd404aef33bfb11f
并得到1) "41"
- AnnKont