[英]How can I connect from Cloud Run Java application to a Cloud SQL database?
I have a Java/Vert.x application deployed as a Cloud Run container.我有一个部署为 Cloud Run 容器的 Java/Vert.x 应用程序。 It's running fine.
它运行良好。 I've tried to access my Cloud SQL MySQL instance to it, but to no avail.
我试图访问我的 Cloud SQL MySQL 实例,但无济于事。 My application hangs as soon as I try to connect to the DB instance create a DataSource.
一旦我尝试连接到创建数据源的数据库实例,我的应用程序就会挂起。
My Cloud Run container is associated with a service account with the Cloud SQL Client role.我的 Cloud Run 容器与具有Cloud SQL 客户端角色的服务帐号相关联。
I've followed the canonical GCP tutorial here: https://cloud.google.com/sql/docs/mysql/connect-run Obviously swapping in my specifics.我在这里遵循了规范的 GCP 教程: https : //cloud.google.com/sql/docs/mysql/connect-run显然交换了我的细节。 Below is the offending code:
以下是违规代码:
private static final String PW = "mypassword";
private static final String CONN_NAME = "/cloudsql/mydatabase-111222:us-west1:my-project";
private DataSource pool;
@Override
public void init() throws Exception {
LOGGER.info("MysqlRepo-init starting...");
// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();
LOGGER.info("MysqlRepo-init 1");
// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", "mydb"));
config.setUsername("root"); // e.g. "root", "postgres"
config.setPassword(PW); // e.g. "my-password"
// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CONN_NAME);
config.addDataSourceProperty("useSSL", "false");
LOGGER.info("MysqlRepo-init 2");
// Initialize the connection pool using the configuration object.
pool = new HikariDataSource(config);
LOGGER.info("MysqlRepo-init 3");
ResultSet rs = pool.getConnection().createStatement().executeQuery("SELECT COUNT(*) col FROM dual WHERE 1=1");
LOGGER.info("MysqlRepo-init Results = " + rs.getFetchSize());
LOGGER.info("...MysqlRepo-init done");
}
My logs stop at "MysqlRepo-init 2" (beyond that, I get Vertx warnings that my main thread is blocked).我的日志停在“MysqlRepo-init 2”(除此之外,我收到 Vertx 警告说我的主线程被阻塞)。
Any thoughts on what I might be missing?关于我可能缺少什么的任何想法?
The problem seems to have something to do with calling this code from a Vert.x verticle.问题似乎与从 Vert.x verticle 调用此代码有关。 When I called it directly from the application's main method, I was able to get useful log messages, which were complaining about the "/cloudsql/" portion of the connection name.
当我直接从应用程序的 main 方法调用它时,我能够获得有用的日志消息,这些消息抱怨连接名称的“/cloudsql/”部分。 That provided enough information to ultimately resolve ths issue.
这提供了足够的信息来最终解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.