即使 Cassandra 宕机,如何加载 spring 应用程序上下文 [英] How to load spring application context even if Cassandra down

查看:35
本文介绍了即使 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.

这篇关于即使 Cassandra 宕机,如何加载 spring 应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆