遵循教程和我的 CloudSqlServlet.java init() 函数:
try {
ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
Map<String, Object> attr = env.getAttributes();
String hostname = (String) attr.get("com.google.appengine.runtime.default_version_hostname");
String url = hostname.contains("localhost:")
? System.getProperty("cloudsql-local") : System.getProperty("cloudsql");
log("connecting to: " + url);
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
throw new ServletException("Unable to connect to Cloud SQL", e);
}
这是我的 appegnine-web.xml:
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<version>1</version>
<threadsafe>true</threadsafe>
<runtime>java8</runtime>
<use-google-connector-j>true</use-google-connector-j>
<service>cloudsql</service>
<system-properties>
<property name="cloudsql" value="jdbc:google:mysql://${INSTANCE_CONNECTION_NAME}/${database}?user=${user}&password=${password}" />
<property name="cloudsql-local" value="jdbc:mysql://google/${database}?useSSL=false&cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=${user}&password=${password}" />
</system-properties>
</appengine-web-app>
该应用程序使用 Maven 编译。然后我在一个终端中运行 appengine 服务器:
mvn appengine:run
在另一个终端中,我将运行 sql 代理:
./cloud_sql_proxy -instances=skeleton-182342:europe-west1:trial1131=tcp:3306
然后当我在本地访问服务器时:localhost:8080/cloudsql
应用程序抛出异常:
原因:java.lang.IllegalArgumentException:无效的 Cloud SQL 实例 [${INSTANCE_CONNECTION_NAME}],表单 [project:region:name] 中的预期值。
在日志中我可以看到属性没有插入到 url 中:
log: CloudSQL: connecting to: jdbc:mysql://google/${database}?useSSL=false&cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=${user}&password=${password}