1

当我尝试运行通过 jdbc 连接到谷歌云实例的脚本时,我不断收到此错误。完全不确定如何解决它:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/cloud/sql/core/CoreSocketFactory
        at com.google.cloud.sql.postgres.SocketFactory.createSocket(SocketFactory.java:73)
        at org.postgresql.core.PGStream.<init>(PGStream.java:73)
        at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:93)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211)
        at org.postgresql.Driver.makeConnection(Driver.java:459)
        at org.postgresql.Driver.connect(Driver.java:261)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:270)
        at App.main(App.java:12)
Caused by: java.lang.ClassNotFoundException: com.google.cloud.sql.core.CoreSocketFactory
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 11 more

连接到 db 的脚本(“..”引用了出于隐私原因未包括在内的实例名称和密码):

import java.sql.Connection;
import java.sql.DriverManager;

public class App
{
    public static void main(String args[])
    {
        Connection c = null;
        try
        {
           Class.forName("org.postgresql.Driver");
           c = DriverManager.getConnection("jdbc:postgresql:///<postgres>?cloudSqlInstance=<...:database>&socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<postgres>&password=<...>");
        }
        catch (Exception e)
        {
           e.printStackTrace();
           System.err.println(e.getClass().getName()+": "+e.getMessage());
           System.exit(0);
        }
        System.out.println("Opened database successfully");
     }
}
4

1 回答 1

1

您正在尝试将socketFactory=com.google.cloud.sql.postgres.SocketFactory参数传递给 JDBC 连接字符串,而com.google.cloud.sql.core.CoreSocketFactory在您的类路径中找不到类。

看起来您没有向类路径添加必需的依赖项。看看 GCP github 手册:https ://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory

例如,如果您使用 Maven,请添加此依赖项

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>postgres-socket-factory</artifactId>
    <version>1.0.15</version>
</dependency>
于 2020-04-19T04:37:50.790 回答