skip to Main Content

I see some weird case. Sometimes my findBy…() method returns null instead of some object inserted and fetched successfully before. After that the needed object fetches fine. In other words sometimes the search is not working.

Spring Boot edition: 1.5.2.RELEASE

spring-boot-starter-data-redis: 1.5.22.RELEASE

"maxmemory-policy" setting is set to "noeviction"

My obj declaration:

@RedisHash("session")
public class Session implements Serializable {

    @Id
    private String id;

    @Indexed
    private Long internalChatId;
    @Indexed
    private boolean active;
    @Indexed
    private String chatId;
}

JPA Repository:

@Repository
public interface SessionRepository extends CrudRepository<Session, String> {

    Session findByInternalChatIdAndActive(Long internalChatId, Boolean isActive);
}

Redis config:

@Bean
    public LettuceConnectionFactory redisConnectionFactory(
        RedisProperties redisProperties) {
        return new LettuceConnectionFactory(
            redisProperties.getRedisHost(),
            redisProperties.getRedisPort());
    }

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

Thanx in advance for any assist.

2

Answers


  1. This should not happen I don’t what is reason. But you can use Option class and if it returns null at least you can avoid exception.
    Something like:

        Optional<Session> findByInternalChatIdAndActive(Long internalChatId, Boolean isActive);
    
    Login or Signup to reply.
  2. We have recently seen similar behavior. In our scenario, we can have multiple threads that read and write to the same repository. Our null return occurs when one thread is doing a save to an object while another is doing a findById for that same object. The findById will occasionally fail. It appears that the save implementation does a delete followed by an add; if the findById gets in during the delete, the null result is returned.

    We’ve had good luck so far in our test programs that can reproduce the null return using a Java Semaphore to gate all access (read, write, delete) to the repository. When the repository access methods are all gated by the same semaphore, we have not seen a null return. Our next step is to try adding the synchronized keyword to the methods in the class that access the repository (as an alternative to using the Semaphore).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search