如何为 Google Cloud SQL 配置 Java Hibernate?

How to configure Java Hibernate for Google Cloud SQL?

我正在使用 Hibernate + Java + Jersey + MYSql,它在本地机器上运行良好。但是我无法在 Google Cloud 上创建到 MySql 的连接。

我认为 MYSql 配置和实例创建在 Google 云上没问题,但我无法通过休眠属性传递所有配置。看这里是什么Google的示例代码:

// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();

// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "postgres"
config.setPassword(DB_PASS); // 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", CLOUD_SQL_CONNECTION_NAME);
config.addDataSourceProperty("useSSL", "false");

// ... Specify additional connection properties here.
// ...

// Initialize the connection pool using the configuration object.
DataSource pool = new HikariDataSource(config);

现在我不知道如何在 Hibernate 中传递 cloudSqlInstancesocketFactory。在这里我尝试传递这些参数但它不起作用:

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://google/pashumandi_db?cloudSqlInstance=pashuserver:asia-south1:mysql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory
hibernate.connection.username = abc_user
hibernate.connection.password = 12345678
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

能否请您告诉我连接 Google 云上的 MySql 的正确休眠配置是什么?谢谢。

对于 Google 云,您可以 select 您的数据库实例,然后在“连接”下,您可以 select 允许来自 Public IP 地址的连接,然后添加您的机器的 IP 地址到授权建立连接的地址列表。从那里您需要做的就是在 URL 中使用您的数据库实例的 public IP 地址。

在 Google Cloud Console 的实例详细信息页面上找到实例的 INSTANCE_CONNECTION_NAME。它使用 PROJECT_ID:REGION:INSTANCE_ID 格式,用于标识您正在连接的 Cloud SQL 实例。

要启用本地 TCP 端口,请将以下内容添加到项目的 app.yaml 文件中:

runtime: java
env: flex
beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>=tcp:<PORT>

然后这是我的 hibernate.properties 文件:

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://172.17.0.1:PORT_NUMBER_IN_YAML_FILE
hibernate.connection.username = DB_USERNAME
hibernate.connection.password = DB_PASSWORD
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.default_schema = DATABASE_NAME
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create

更多详情可以访问:https://cloud.google.com/sql/docs/mysql/connect-app-engine