When connecting to Google Cloud Spanner Emulator with jdbc, credentials that should not be needed are required

扶醉桌前 提交于 2021-02-11 13:00:29

问题


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:

  1. Setting the SPANNER_EMULATOR_HOST environment variable to the address of the emulator. In this case that would be localhost: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 the localhost:9010 part from the JDBC connection URL when you set the SPANNER_EMULATOR_HOST environment variable.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!