首页 > 解决方案 > 由于 Spring 引导版本升级到 2.3.1,Spring 数据 cassandra 出现问题

问题描述

由于 Spring boot 2.3 版本中对 docker 镜像支持的改进,我们决定迁移到这个版本。在我们的项目中,我们使用 Cassandra 作为数据库之一。但是除了迁移到 cassandra 驱动程序版本 4 之外,spring data cassandra 似乎发生了很多变化。问题是这个不允许应用程序启动的异常,

 java.lang.IllegalStateException: Since you provided explicit contact points, the local DC must be explicitly set (see basic.load-balancing-policy.local-datacenter in the config, or set it programmatically with SessionBuilder.withLocalDatacenter)

现在,我在网上搜索并发现有人建议:

将此属性添加到我的 application.properties:

spring.data.cassandra.local-datacenter=datacenter1 (in my case since in the exception that it throws, it's mentioned that the local datacenter is - datacenter1)

并在创建 CqlSession bean 时指定它,我正在这样做:

public CqlSession session() {

     String containerIpAddress = getContactPoints();
     int containerPort = getPort();
     InetSocketAddress containerEndPoint = new InetSocketAddress(containerIpAddress, containerPort);

    return CqlSession.builder().withLocalDatacenter(getLocalDataCenter())
            .addContactPoint(containerEndPoint)
            .withAuthCredentials(dbProperties.getCassandraUserName(), dbProperties.getCassandraPassword())
            .withKeyspace(getKeyspaceName()).build(); }

但是我仍然被卡住并且无法启动应用程序。如何解决这个问题?

标签: spring-bootspring-data-cassandracassandra-driver

解决方案


使用此配置对我有用

public CqlSession session() {
        return CqlSession.builder().withLocalDatacenter(getLocalDataCenter())
                .addContactPoint(InetSocketAddress.createUnresolved(getContactPoints(), 9042))
                //.withAuthCredentials(dbProperties.getCassandraUserName(), dbProperties.getCassandraPassword())
                .withKeyspace(getKeyspaceName()).build();
    }


@Bean
    @ConditionalOnMissingBean
    public CassandraTemplate cassandraTemplate(CqlSession session) throws Exception {
        return new CassandraTemplate(session);
    }

推荐阅读