问题
When I try to connect using the Google Cloud Spanner Open Source JDBC Driver, I get the following error message:
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more
URI:jdbc:cloudspanner:localhost:9010/projects/my-project/instances/my-instance/databases/my-database
I don't think the emulator needs any credentials to work locally. Is there a way around this error? Thank you.
回答1:
You are correct that the emulator does not require any credentials. The reason that you are getting this error, is that the JDBC driver does not know that you are trying to connect to the emulator. Instead, it thinks you are trying to connect to some server at localhost:9010, which could be the official emulator or any other emulator or mock server.
There are two ways to connect to the emulator:
- Setting the
SPANNER_EMULATOR_HOST
environment variable to the address of the emulator. In this case that would belocalhost:9010
. When this environment variable is set, the JDBC driver knows that you are trying to connect to the emulator and will ensure that no credentials are required or used. You can omit thelocalhost:9010
part from the JDBC connection URL when you set theSPANNER_EMULATOR_HOST
environment variable. - Using a specific host name in the JDBC connection URL. This is the method that you are trying to use in your example. In order to instruct the JDBC driver not to use any credentials, you need to include
usePlainText=true
in the connection URL. This will tell the JDBC driver to create a plain text connection (i.e. no SSL) and not to use any credentials.
The following is a valid example of how to connect to the emulator by specifying a host name in the URL:
try (Connection connection = DriverManager.getConnection(
"jdbc:cloudspanner://localhost:9010/projects/test-project/instances/test-instance/databases/test-db;usePlainText=true")) {
try (ResultSet rs = connection.createStatement().executeQuery("SELECT 1")) {
while (rs.next()) {
System.out.printf("%d%n", rs.getLong(1));
}
}
}
来源:https://stackoverflow.com/questions/63879318/when-connecting-to-google-cloud-spanner-emulator-with-jdbc-credentials-that-sho