OK 所以我正在尝试制作一个使用 cloudSQL 代理发布到 cloudSQL 实例的 Java 服务器,但我被卡住了。
我在本地计算机上成功启动了代理和服务器:
./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 servlet:
@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在DriverManager类的getConnection((方法中抛出:
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 天。
事实证明我已经安装了云SDK,但是我没有通过先在命令行上运行" gcloud auth login"来在本地服务器上授权它。