Использование CloudSQL Proxy для подключения к Google CloudSQL

Итак, я пытаюсь создать сервер Java, который отправляет сообщения в экземпляр CloudSQL, используя прокси-сервер cloudSQL, и я застрял.

Я успешно запустил прокси и сервер на моей локальной машине:

./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:3306 \
                  -credential_file=<PATH_TO_KEY_FILE> &

Это сервер:

public class PostMainServer {
    public static void main(String[] args) throws Exception {

            Server server = new Server(7070);
            ServletContextHandler handler = new ServletContextHandler(server, "/post");
            handler.addServlet(Servlet.class, "/");
            server.start();
        }
}

Это сервлет Jetty, который использует сервер:

@SuppressWarnings({ "deprecation", "resource" })
    protected void doPost(HttpServletRequest request,     HttpServletResponse response) throws ServletException, IOException {

    // ...... logic goes here...... //

    // Now it's time to connect to the CloudSQL instance.
        String jdbcUrl = String.format(
                "jdbc:mysql://google/%s?cloudSqlInstance=%s&"
                   +     "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
                databaseName,
                instanceConnectionName);

                 Connection conn = DriverManager.
getConnection(jdbcUrl, username,     password); //<----- The Exception is thrown here....

    // the rest below.....
}

Это ошибка, которую я получаю из консоли, когда использую Postman для выполнения запроса POST:

Apr 09, 2017 6:30:21 PM com.google.cloud.sql.mysql.SocketFactory connect
INFO: Connecting to Cloud SQL instance [INSTANCE-NAME].
Apr 09, 2017 6:30:21 PM com.google.cloud.sql.mysql.SslSocketFactory getInstance
INFO: First Cloud SQL connection, generating RSA key pair.
java.sql.SQLNonTransientConnectionException: Could not create connection to database server.

При прохождении через отладчик SQLException вызывается здесь в методе getConnection() класса DriverManager:

        SQLException reason = null;

        for(DriverInfo aDriver : registeredDrivers) {
            // If the caller does not have permission to load the driver then
            // skip it.
            if(isDriverAllowed(aDriver.driver, callerCL)) {
                try {
                    println("    trying " + aDriver.driver.getClass().getName());
                    Connection con = aDriver.driver.connect(url, info);
                    if (con != null) {
                        // Success!
                        println("getConnection returning " + aDriver.driver.getClass().getName());
                        return (con);
                    }
                } catch (SQLException ex) {
                    if (reason == null) {
                        reason = ex; // <--------- THIS LINE IS REACHED
                    }
                }

            } // The rest of the method below.....

Наконец, прокси-сервер не регистрирует никаких подключений:

2017/04/09 18:29:21 Listening on [INSTANCE-CONNECTION-NAME]
2017/04/09 18:29:21 Ready for new connections...

Если предположить, что имя пользователя и пароль верны, что может быть причиной этого отказа подключиться к прокси-серверу? Я застрял на 2 дня сейчас.

1 ответ

Итак, получается, что у меня установлен облачный SDK, но я не авторизовал его на локальном сервере, выполнив сначала "gcloud auth login" в командной строке.

Другие вопросы по тегам