springelasticsearchspring-data-elasticsearchspring-actuator

How can I check `elasticsearch is down` condition in my service?


I have some service. I need return data from elastic search if it available or return from DB:

@Service
class DefaulUserService implements UserService {

    private final DbDao dbDao;
    private final ElasticsearchDao elasticsearchDao;

    DefaultDoctorService(DbDao dbDao, ElasticsearchDao elasticsearchDao) {
        this.dbDao= dbDao;
        this.elasticsearchDao= elasticsearchDao;
    }

    @Override
    public List<User> findAll() {
       if(elasticsearch is down){
             return dbDao.findAll();
        } else {
             return elasticsearchDao.findAll();
       }
    }
}

How can I check the elasticsearch is down condition in my service?


Solution

  • If it's truly down, elasticsearchDao.findAll(); should surely raise an exception, right?

    @Service
    class DefaultUserService implements UserService {
    
        private final DbDao dbDao;
        private final ElasticsearchDao elasticsearchDao;
    
        DefaultDoctorService(DbDao dbDao, ElasticsearchDao elasticsearchDao) {
            this.dbDao= dbDao;
            this.elasticsearchDao= elasticsearchDao;
        }
    
        @Override
        public List<User> findAll() {
            try {
                return elasticsearchDao.findAll();
            }
            catch(Exception e) {
                return dbDao.findAll();
            }
        }
    }
    

    Obviously you'd have to pick a more appropriate type of exception to catch.