当前位置: 首页 > 知识库问答 >
问题:

无法使用springboot连接到不同主机上的两个数据库

尤研
2023-03-14

我无法连接到驻留在不同主机上的两个数据库。我已经定义了主要和次要数据源配置类。交叉检查了我的凭据。用telnet命令测试了可达性。但是不知何故,我能够从我的 localhost 环境连接到这两个数据库。我想我能够通过 localhost 连接到这些数据库,因为主机是一样的。但是不知道生产中有什么问题。这是我的文件。

application.properties

server.port=9393
server.sessionTimeout = 30

spring.profiles.active = dev
spring.jackson.serialization.fail-on-empty-beans = false
spring.mvc.throw-exception-if-no-handler-found=true

######production#################
server.address = [some IP]
spring.data.mongodb.host=[some IP]
spring.data.mongodb.port=27017
spring.data.mongodb.database=MongoLog
#########################

#######localhost###########
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=MongoLog
###########################

#production DB-1
spring.datasource.jdbc-url=jdbc:mysql://[some IP-1]:3306/proDB1?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=secret@123

#localhost DB1--->
#spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/proDB1?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
#spring.datasource.username=root
#spring.datasource.password=root

#production DB-2
spring.seconddatasource.jdbc-url=jdbc:mysql://[some IP-2]:3306/proDB2?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
spring.seconddatasource.username=root
spring.seconddatasource.password=secret@321

#localhost DB2--->
#spring.seconddatasource.jdbc-url=jdbc:mysql://localhost:3306/proDB2?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
#spring.seconddatasource.username=root
#spring.seconddatasource.password=root

spring.jpa.database=default
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

# TOMCAT
tomcat.accessLogEnabled=false
tomcat.protocolHeader=x-forwarded-proto
tomcat.remoteIpHeader=x-forwarded-for
tomcat.backgroundProcessorDelay=30

主数据源类

package com.product.dailyReport;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
          entityManagerFactoryRef = "primaryEntityManagerFactory",
          transactionManagerRef = "primaryTransactionManager",
          basePackages = { "com.product.dailyReport.repository" }
          
        
        )
public class PrimaryDBConfig {
    @Bean(name="primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("primaryDataSource") DataSource primaryDataSource) {
        return builder
                .dataSource(primaryDataSource)
                .packages("com.product.dailyReport")
                .build();
    }

    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager primaryTransactionManager(
            @Qualifier("primaryEntityManagerFactory") EntityManagerFactory primaryEntityManagerFactory) {
        return new JpaTransactionManager(primaryEntityManagerFactory);
    }
}

辅助数据源类

package com.product.dailyReport;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  entityManagerFactoryRef = "secondaryEntityManagerFactory",
  transactionManagerRef = "secondaryTransactionManager",
  basePackages = { "com.product.dailyReport.colombo.repository" }
)
public class SecondaryDBConfig {
    @Bean(name="secondaryDataSource")
    @ConfigurationProperties(prefix="spring.seconddatasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        return builder
                .dataSource(secondaryDataSource)
                .packages("com.product.dailyReport")
                .build();
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager(
            @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {
        return new JpaTransactionManager(secondaryEntityManagerFactory);
    }
}

绒球.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.crbt</groupId>
    <artifactId>DailyReport</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>DailyReport</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Spring boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency> -->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Spring boot development tools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

        

        <!-- MySQL database connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.31</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client 
<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.3.0</version>
</dependency>
        -->

        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.5.7</version>
        </dependency>

        <!-- Java EE based dependency injection -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

    
        <!-- EMail validator -->
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.4.1</version>
        </dependency>
        <!-- JSON/XML tool -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.7.0</version>
</dependency>


<!-- https://mvnrepository.com/artifact/com.squareup.okio/okio -->
<dependency>
    <groupId>com.squareup.okio</groupId>
    <artifactId>okio</artifactId>
    <version>1.12.0</version>
</dependency>



        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>
        
        
        
        
                        <!-- API, java.xml.bind module -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.2</version>
</dependency>

<!-- Runtime, com.sun.xml.bind module -->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
</dependency>
        
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

在 localhost 环境下,一切都很好,也就是说,我可以使用上述设置从 localhost 连接到两个数据库,但在正式生产环境下,我得到了com. mysql.jdbc.例外.jdbc4。MySQLNonTranentConnectionException:无法创建与数据库服务器的连接。尝试重新连接3次。放弃。下面是完整的堆栈,它有一些与hikari相关的东西…不知道是什么:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.Util.getInstance(Util.java:383) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1023) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:997) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:983) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:928) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2407) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2328) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) ~[mysql-connector-java-5.1.31.jar!/:na]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344) ~[mysql-connector-java-5.1.31.jar!/:na]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) [HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) [HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-4.0.3.jar!/:na]
        at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-4.0.3.jar!/:na]
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) [hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]

共有1个答案

吴松
2023-03-14

将以下内容添加到您的< code > application . properties 中:

spring.datasource.url=jdbc:mysql://[some IP-1]:3306/proDB1?useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.seconddatasource.url=jdbc:mysql://[some IP-2]:3306/proDB2?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
spring.seconddatasource.driver-class-name=com.mysql.cj.jdbc.Driver

实际上与“jdbc-url”中已经存在的值相同。

它与hiraki和驱动程序如何读取数据库url有关。此处的更多信息:如何在Spring Boot中将HikariCP与两个数据源结合使用Flyway

 类似资料:
  • 我正在尝试从Spring Boot应用程序连接到mySQL数据库。然而,当我试图运行它时,它显示出错误。 我如何解决这个问题? 错误 从我的文件中添加代码片段 pom。xml 应用属性 堆栈跟踪 我还没有在sql中手动创建表,因为我认为spring.jpa.hibernate.ddl-Auto=date应该这样做

  • SMTP错误:无法连接到SMTP主机。无法发送消息。 邮件程序错误:SMTP错误:无法连接到SMTP主机。 我似乎找不到让PHPMailer在CentOS下工作的方法。邮件在XAMPP的Windows下工作正常,但我总是在Linux下遇到这个错误。 SMTP服务器是一个在端口25上侦听的Lotus Domino,CentOS机器根本没有防火墙,奇怪的是,即使是mail()也不能工作。它不返回任何内

  • df1有每月时间索引,df2有季度时间索引。df1和df2有不同的行数和列数,我想:(1)并排连接它们并保持它们的索引。(2)输出到excel文件。 我尝试过pd.concat,但是这种方法连接基于我不想要的数据帧索引之一的数据帧 excel中的预期结果:

  • 问题内容: 我正在尝试使用PyMySQL连接到本地主机上的MySQL: 但是(在Python 2.7和Python 3.2上)我得到了错误: socket.error:[Errno 111]连接被拒绝 pymysql.err.OperationalError:(2003年,“无法连接到’localhost’(111)上的MySQL服务器”) 我确定mysqld正在运行,因为我可以使用command

  • 我是一个新手,需要一些帮助。. 我正在使用Selenium 2.2.0和FF v7。Windows XP上的0.1 我已经成功地在IE中录制并回放了一个java脚本,但是每当我尝试在FF中执行相同的脚本时,我都会收到以下错误消息: 45000 ms后无法连接到端口7055上的主机127.0.0.1 我在很多地方读到,如果我将firefox版本降级到3.6,脚本将运行良好,但我并不热衷于降级。有人能

  • 我试图部署一个与主机数据库一起工作的Drupal6Docker容器(在将其部署到远程数据库之前出于测试目的),但它就是不想工作,尽管我找到了不同的建议。(特别是在这个来自Docker容器内部的问题中,我如何连接到机器的本地主机?当它谈到主机模式时,所以即使这个问题看起来很像,它也不觉得它是重复的) DockerFile Docker-compose.yml 对于数据库连接,我指定了以下设置: 驱动

  • 问题内容: 以下是我发送邮件的代码: 但是当我运行代码时,它给了我以下异常。 当我ping到它时,它给我的答复没有任何问题。我在用 请帮我解决这个问题。 问题答案: 这是这两行让我感到困扰的问题: 并添加了这一行: 删除并添加以上代码行后,它可以正常工作。

  • 我正在尝试从我的java发送电子邮件,但我无法连接到我的主机。这里是我的代码: 这里是我的代码: 这里又是我的报告错误: 有人能帮帮我吗?:(