即使 Cassandra 宕机,如何加载 spring 应用程序上下文

问题描述:

使用时

@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;
    }

com.foo 包中有一个接口扩展了 CrudRepository.

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.

我目前观察到的行为是抛出 NoHostAvailableException 并且 Web 容器没有启动.

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

我想出了一个解决方案.我从存储库中删除了 @EnableCassandraRepositories(basePackages={"com.foo"}) 注释,并在我的配置中定义了一个 Bean,它将返回我的存储库.删除 EnableCassandraRepositories 允许延迟加载存储库.我的 Config 中的这个新 bean 允许我使用 RepositoryFactorySupport getRepository() 方法实例化我的存储库.我将这个 bean 注释为惰性,并确保对 bean 的引用也是惰性的.

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

公共接口 IBarRepository 扩展了 CrudRepository{}

我的配置文件现在看起来像

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.