How to load spring application context even if Cassandra down

雨燕双飞 提交于 2019-12-13 02:13:52

问题


When using

@Configuration
@EnableCassandraRepositories(basePackages={"com.foo"})
public class CassandraConfig{
@Bean
    public CassandraClusterFactoryBean cluster()
    {

        final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
        cluster.setContactPoints(nodesRead);
        cluster.setPort(port);

        return cluster;
    }

Where in the com.foo package there is a interface that extends CrudRepository.

Is there a way to make it so that at startup time an exception is not thrown if the database is down?

Ideally what occurs is that we startup and anytime you call a method on the repository, it will first attempt to connect to the database and then if the database is still down return an error saying can't connect.

The behavior I currently observe is that NoHostAvailableException is thrown and the web container does not start up.


回答1:


I was able to come up with a solution. I removed the @EnableCassandraRepositories(basePackages={"com.foo"}) annotation from the repository and defined a Bean in my Config that would return my repository. Removing the EnableCassandraRepositories allowed lazy loading of the repository. This new bean in my Config allowed me to instantiate my repository using the RepositoryFactorySupport getRepository() method. I annotated this bean as lazy and made sure references to the bean were also lazy.

Assume my repository looks like the following

public interface IBarRepository extends CrudRepository<Bar, BarKey>{}

My Config file now looks like

@Configuration

public class CassandraConfig{
@Bean
@Lazy(value=true)
public IBarRepository barRepository() throws Exception    
{
  final RepositoryFactorySupport support = CassandraRepositoryFactory(cassandraTemplate());
  return support.getRepository(IBarRepository.class); 
}
@Bean
@Lazy(value=true)
public CassandraClusterFactoryBean cluster()
{

    final CassandraClusterFactoryBean cluster = new   CassandraClusterFactoryBean();
    cluster.setContactPoints(nodesRead);
    cluster.setPort(port);

    return cluster;
}
//More beans down here defining things like cluster, mappingContext, session, etc.


来源:https://stackoverflow.com/questions/33745615/how-to-load-spring-application-context-even-if-cassandra-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!