对象未存储在Redis缓存中

时间:2019-04-06 18:03:31

标签: spring-boot redis

我有一个User类,如下所示:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("loggedInUser")
public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -1625655374442156393L;
    @Id
    private Long userId;
    private String username;
    private String role;

}

在登录时,我通过repository.save()保存了对象,但是在通过keys *从redis获取数据时,我在其中找不到loggingInUser。我正在使用的存储库是:

@Repository
public interface AppAuthenticationRepository extends JpaRepository<User, Long> {

    LoggedInUser findByUsername(String username);
    LoggedInUser deleteByUsername(String username);

}

1 个答案:

答案 0 :(得分:0)

您是否设置了适当的配置类?例如:

@Configuration
@EnableRedisRepositories
public class RedisConfig {

  @Bean
  public RedisConnectionFactory connectionFactory() {
    return new JedisConnectionFactory();
  }

  @Bean
  public RedisTemplate<?, ?> redisTemplate() {
    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
    return template;
  }
}

一旦您设置了Redis配置,就可以这样定义您的存储库:

@Repository
public interface AppAuthenticationRepository extends CrudRepository<LoggedInUser, Long> {
    LoggedInUser findByUsername(String username);
    LoggedInUser deleteByUsername(String username);
}

您也有JpaRepository<User, Long>,但返回LoggedInUser。我会尝试CrudRepository<LoggedInUser, Long>

Spring Data Redis documentation有一个很好的用法示例,它也应该有所帮助。