Java idiomatic client for Cloud Spanner.
If you are using Maven with BOM, add this to your pom.xml file:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.70.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
</dependency>
If you are using Maven without the BOM, add this to your dependencies:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
<version>6.102.0</version>
</dependency>
If you are using Gradle 5.x or later, add this to your dependencies:
implementation platform('com.google.cloud:libraries-bom:26.70.0')
implementation 'com.google.cloud:google-cloud-spanner'If you are using Gradle without BOM, add this to your dependencies:
implementation 'com.google.cloud:google-cloud-spanner:6.102.1'If you are using SBT, add this to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.102.1"See the Authentication section in the base directory's README.
The client application making API calls must be granted authorization scopes required for the desired Cloud Spanner APIs, and the authenticated principal must have the IAM role(s) required to access GCP resources using the Cloud Spanner API calls.
You will need a Google Cloud Platform Console project with the Cloud Spanner API enabled.
You will need to enable billing to use Google Cloud Spanner.
Follow these instructions to get your project set up. You will also need to set up the local development environment by
installing the Google Cloud Command Line Interface and running the following commands in command line:
gcloud auth login and gcloud config set project [YOUR PROJECT ID].
You'll need to obtain the google-cloud-spanner library. See the Quickstart section
to add google-cloud-spanner as a dependency in your code.
Cloud Spanner is a fully managed, mission-critical, relational database service that offers transactional consistency at global scale, schemas, SQL (ANSI 2011 with extensions), and automatic, synchronous replication for high availability. Be sure to activate the Cloud Spanner API on the Developer's Console to use Cloud Spanner from your project.
See the Cloud Spanner client library docs to learn how to use this Cloud Spanner Client Library.
Here is a code snippet showing a simple usage example. Add the following imports at the top of your file:
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;Then, to make a query to Spanner, use the following code:
// Instantiates a client
SpannerOptions options = SpannerOptions.newBuilder().build();
Spanner spanner = options.getService();
String instance = "my-instance";
String database = "my-database";
try {
// Creates a database client
DatabaseClient dbClient = spanner.getDatabaseClient(
DatabaseId.of(options.getProjectId(), instance, database));
// Queries the database
try (ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"))) {
// Prints the results
while (resultSet.next()) {
System.out.printf("%d\n", resultSet.getLong(0));
}
}
} finally {
// Closes the client which will free up the resources used
spanner.close();
}In DatabaseSelect.java we put together all the code shown above in a single program.
The Cloud Spanner client maintains a session pool, as sessions are expensive to create and are intended to be long-lived. The client automatically takes a session from the pool and uses this executing queries and transactions. See Session Pool and Channel Pool Configuration for in-depth background information about sessions and gRPC channels and how these are handled in the Cloud Spanner Java client.
Cloud Spanner client supports client-side metrics that you can use along with server-side metrics to optimize performance and troubleshoot performance issues if they occur.
Client-side metrics are measured from the time a request leaves your application to the time your application receives the response. In contrast, server-side metrics are measured from the time Spanner receives a request until the last byte of data is sent to the client.
These metrics are enabled by default. You can opt out of using client-side metrics with the following code:
SpannerOptions options = SpannerOptions.newBuilder()
.setBuiltInMetricsEnabled(false)
.build();
You can also disable these metrics by setting SPANNER_DISABLE_BUILTIN_METRICS to true.
Note: Client-side metrics needs
monitoring.timeSeries.createIAM permission to export metrics data. Ask your administrator to grant your service account the Monitoring Metric Writer (roles/monitoring.metricWriter) IAM role on the project.
Cloud Spanner client supports OpenTelemetry Traces, which gives insight into the client internals and aids in debugging/troubleshooting production issues.
By default, the functionality is disabled. You need to add OpenTelemetry dependencies, enable OpenTelemetry traces and must configure the OpenTelemetry with appropriate exporters at the startup of your application.
See Configure client-side tracing for more details on configuring traces.
If you are using Maven, add this to your pom.xml file
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
<version>{opentelemetry.version}</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk-trace</artifactId>
<version>{opentelemetry.version}</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
<version>{opentelemetry.version}</version>
</dependency>If you are using Gradle, add this to your dependencies
compile 'io.opentelemetry:opentelemetry-sdk:{opentelemetry.version}'
compile 'io.opentelemetry:opentelemetry-sdk-trace:{opentelemetry.version}'
compile 'io.opentelemetry:opentelemetry-exporter-oltp:{opentelemetry.version}'Note: Enabling OpenTelemetry traces will automatically disable OpenCensus traces.
// Enable OpenTelemetry traces
SpannerOptions.enableOpenTelemetryTraces();
// Create a new tracer provider
SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
// Use Otlp exporter or any other exporter of your choice.
.addSpanProcessor(SimpleSpanProcessor.builder(OtlpGrpcSpanExporter
.builder().build()).build())
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setTracerProvider(sdkTracerProvider)
.build()
SpannerOptions options = SpannerOptions.newBuilder()
// Inject OpenTelemetry object via Spanner Options or register OpenTelmetry object as Global
.setOpenTelemetry(openTelemetry)
.build();
Spanner spanner = options.getService();The OpenTelemetry traces that are generated by the Java client include any request and transaction
tags that have been set. The traces can also include the SQL statements that are executed and the
name of the thread that executes the statement. Enable this with the enableExtendedTracing
option:
SpannerOptions options = SpannerOptions.newBuilder()
.setOpenTelemetry(openTelemetry)
.setEnableExtendedTracing(true)
.build();
This option can also be enabled by setting the environment variable
SPANNER_ENABLE_EXTENDED_TRACING=true.
You can enable tracing of each API call that the Spanner client executes with the enableApiTracing
option. These traces also include any retry attempts for an API call:
SpannerOptions options = SpannerOptions.newBuilder()
.setOpenTelemetry(openTelemetry)
.setEnableApiTracing(true)
.build();
This option can also be enabled by setting the environment variable
SPANNER_ENABLE_API_TRACING=true.
Note: The attribute keys that are used for additional information about retry attempts and the number of requests might change in a future release.
In addition to client-side tracing, you can opt in for end-to-end tracing. End-to-end tracing helps you understand and debug latency issues that are specific to Spanner such as the following:
- Identify whether the latency is due to network latency between your application and Spanner, or if the latency is occurring within Spanner.
- Identify the Google Cloud regions that your application requests are being routed through and if there is a cross-region request. A cross-region request usually means higher latencies between your application and Spanner.
SpannerOptions options = SpannerOptions.newBuilder()
.setOpenTelemetry(openTelemetry)
.setEnableEndToEndTracing(true)
.build();
Refer to Configure end-to-end tracing to configure end-to-end tracing and to understand its attributes.
Note: End-to-end traces can only be exported to Cloud Trace.
Note: OpenCensus project is deprecated. See Sunsetting OpenCensus. We recommend migrating to OpenTelemetry, the successor project.
Using the OpenTelemetry OpenCensus Bridge, you can immediately begin exporting your metrics and traces with OpenTelemetry.
Disable OpenCensus metrics for Spanner by including the following code if you still possess OpenCensus dependencies and exporter.
SpannerOptions.disableOpenCensusMetrics();Enabling OpenTelemetry traces for Spanner will automatically disable OpenCensus traces.
SpannerOptions.enableOpenTelemetryTraces();Remove any OpenCensus-related code and dependencies from your codebase if all your dependencies are ready to move to OpenTelemetry.
- Remove the OpenCensus Exporters which were configured here
- Remove SpannerRPCViews reference which were configured here
- Remove the OpenCensus dependencies which were added here
Update your dashboards and alerts to reflect below changes
- Metrics name :
cloud.google.com/javaprefix has been removed from OpenTelemery metrics and instead has been added as Instrumenation Scope. - Metrics namespace : OpenTelmetry exporters uses
workload.googleapis.comnamespace opposed tocustom.googleapis.comwith OpenCensus.
Samples are in the samples/ directory.
| Sample | Source Code | Try it |
|---|---|---|
| Add And Drop Database Role | source code | ![]() |
| Add Json Column Sample | source code | ![]() |
| Add Jsonb Column Sample | source code | ![]() |
| Add Numeric Column Sample | source code | ![]() |
| Add Proto Column Sample | source code | ![]() |
| Alter Sequence Sample | source code | ![]() |
| Alter Table With Foreign Key Delete Cascade Sample | source code | ![]() |
| Async Dml Example | source code | ![]() |
| Async Query Example | source code | ![]() |
| Async Query To List Async Example | source code | ![]() |
| Async Read Example | source code | ![]() |
| Async Read Only Transaction Example | source code | ![]() |
| Async Read Row Example | source code | ![]() |
| Async Read Using Index Example | source code | ![]() |
| Async Runner Example | source code | ![]() |
| Async Transaction Manager Example | source code | ![]() |
| Batch Sample | source code | ![]() |
| Batch Write At Least Once Sample | source code | ![]() |
| Change Streams Txn Exclusion Sample | source code | ![]() |
| Copy Backup Sample | source code | ![]() |
| Copy Backup With Multi Region Encryption Key | source code | ![]() |
| Create Backup With Encryption Key | source code | ![]() |
| Create Backup With Multi Region Encryption Key | source code | ![]() |
| Create Database With Default Leader Sample | source code | ![]() |
| Create Database With Encryption Key | source code | ![]() |
| Create Database With Multi Region Encryption Key | source code | ![]() |
| Create Database With Version Retention Period Sample | source code | ![]() |
| Create Full Backup Schedule Sample | source code | ![]() |
| Create Incremental Backup Schedule Sample | source code | ![]() |
| Create Instance Config Sample | source code | ![]() |
| Create Instance Example | source code | ![]() |
| Create Instance Partition Sample | source code | ![]() |
| Create Instance With Asymmetric Autoscaling Config Example | source code | ![]() |
| Create Instance With Autoscaling Config Example | source code | ![]() |
| Create Instance With Processing Units Example | source code | ![]() |
| Create Instance Without Default Backup Schedules Example | source code | ![]() |
| Create Sequence Sample | source code | ![]() |
| Create Table With Foreign Key Delete Cascade Sample | source code | ![]() |
| Custom Timeout And Retry Settings Example | source code | ![]() |
| Database Add Split Points Sample | source code | ![]() |
| Delete Backup Schedule Sample | source code | ![]() |
| Delete Instance Config Sample | source code | ![]() |
| Delete Using Dml Returning Sample | source code | ![]() |
| Directed Read Sample | source code | ![]() |
| Drop Foreign Key Constraint Delete Cascade Sample | source code | ![]() |
| Drop Sequence Sample | source code | ![]() |
| Enable Fine Grained Access | source code | ![]() |
| Get Backup Schedule Sample | source code | ![]() |
| Get Commit Stats Sample | source code | ![]() |
| Get Database Ddl Sample | source code | ![]() |
| Get Instance Config Sample | source code | ![]() |
| Insert Using Dml Returning Sample | source code | ![]() |
| Last Statement Sample | source code | ![]() |
| List Backup Schedules Sample | source code | ![]() |
| List Database Roles | source code | ![]() |
| List Databases Sample | source code | ![]() |
| List Instance Config Operations Sample | source code | ![]() |
| List Instance Configs Sample | source code | ![]() |
| Pg Alter Sequence Sample | source code | ![]() |
| Pg Async Query To List Async Example | source code | ![]() |
| Pg Async Runner Example | source code | ![]() |
| Pg Async Transaction Manager Example | source code | ![]() |
| Pg Batch Dml Sample | source code | ![]() |
| Pg Case Sensitivity Sample | source code | ![]() |
| Pg Create Sequence Sample | source code | ![]() |
| Pg Delete Using Dml Returning Sample | source code | ![]() |
| Pg Drop Sequence Sample | source code | ![]() |
| Pg Insert Using Dml Returning Sample | source code | ![]() |
| Pg Interleaved Table Sample | source code | ![]() |
| Pg Last Statement Sample | source code | ![]() |
| Pg Partitioned Dml Sample | source code | ![]() |
| Pg Query With Numeric Parameter Sample | source code | ![]() |
| Pg Spanner Sample | source code | ![]() |
| Pg Update Using Dml Returning Sample | source code | ![]() |
| Query Information Schema Database Options Sample | source code | ![]() |
| Query With Json Parameter Sample | source code | ![]() |
| Query With Jsonb Parameter Sample | source code | ![]() |
| Query With Numeric Parameter Sample | source code | ![]() |
| Query With Proto Parameter Sample | source code | ![]() |
| Quickstart Sample | source code | ![]() |
| Read Data With Database Role | source code | ![]() |
| Restore Backup With Encryption Key | source code | ![]() |
| Restore Backup With Multi Region Encryption Key | source code | ![]() |
| Set Max Commit Delay Sample | source code | ![]() |
| Singer Proto | source code | ![]() |
| Spanner Graph Sample | source code | ![]() |
| Spanner Sample | source code | ![]() |
| Statement Timeout Example | source code | ![]() |
| Tag Sample | source code | ![]() |
| Tracing Sample | source code | ![]() |
| Transaction Timeout Example | source code | ![]() |
| Unnamed Parameters Example | source code | ![]() |
| Update Backup Schedule Sample | source code | ![]() |
| Update Database Sample | source code | ![]() |
| Update Database With Default Leader Sample | source code | ![]() |
| Update Instance Config Sample | source code | ![]() |
| Update Instance Default Backup Schedule Type Example | source code | ![]() |
| Update Instance Example | source code | ![]() |
| Update Json Data Sample | source code | ![]() |
| Update Jsonb Data Sample | source code | ![]() |
| Update Numeric Data Sample | source code | ![]() |
| Update Proto Data Sample | source code | ![]() |
| Update Proto Data Sample Using Dml | source code | ![]() |
| Update Using Dml Returning Sample | source code | ![]() |
| Add And Drop Database Role | source code | ![]() |
| Add Json Column Sample | source code | ![]() |
| Add Jsonb Column Sample | source code | ![]() |
| Add Numeric Column Sample | source code | ![]() |
| Alter Sequence Sample | source code | ![]() |
| Alter Table With Foreign Key Delete Cascade Sample | source code | ![]() |
| Copy Backup Sample | source code | ![]() |
| Create Backup With Encryption Key | source code | ![]() |
| Create Database With Default Leader Sample | source code | ![]() |
| Create Database With Encryption Key | source code | ![]() |
| Create Database With Version Retention Period Sample | source code | ![]() |
| Create Instance Config Sample | source code | ![]() |
| Create Instance Example | source code | ![]() |
| Create Instance With Autoscaling Config Example | source code | ![]() |
| Create Instance With Processing Units Example | source code | ![]() |
| Create Sequence Sample | source code | ![]() |
| Create Table With Foreign Key Delete Cascade Sample | source code | ![]() |
| Delete Instance Config Sample | source code | ![]() |
| Drop Foreign Key Constraint Delete Cascade Sample | source code | ![]() |
| Drop Sequence Sample | source code | ![]() |
| Enable Fine Grained Access | source code | ![]() |
| Get Database Ddl Sample | source code | ![]() |
| Get Instance Config Sample | source code | ![]() |
| List Database Roles | source code | ![]() |
| List Databases Sample | source code | ![]() |
| List Instance Config Operations Sample | source code | ![]() |
| List Instance Configs Sample | source code | ![]() |
| Pg Alter Sequence Sample | source code | ![]() |
| Pg Case Sensitivity Sample | source code | ![]() |
| Pg Create Sequence Sample | source code | ![]() |
| Pg Drop Sequence Sample | source code | ![]() |
| Pg Interleaved Table Sample | source code | ![]() |
| Pg Spanner Sample | source code | ![]() |
| Restore Backup With Encryption Key | source code | ![]() |
| Spanner Sample | source code | ![]() |
| Update Database Sample | source code | ![]() |
| Update Database With Default Leader Sample | source code | ![]() |
| Update Instance Config Sample | source code | ![]() |
To get help, follow the instructions in the shared Troubleshooting document.
Cloud Spanner uses gRPC for the transport layer.
Java 8 or above is required for using this client.
Google's Java client libraries, Google Cloud Client Libraries and Google Cloud API Libraries, follow the Oracle Java SE support roadmap (see the Oracle Java SE Product Releases section).
In general, new feature development occurs with support for the lowest Java LTS version covered by Oracle's Premier Support (which typically lasts 5 years from initial General Availability). If the minimum required JVM for a given library is changed, it is accompanied by a semver major release.
Java 11 and (in September 2021) Java 17 are the best choices for new development.
Google tests its client libraries with all current LTS versions covered by Oracle's Extended Support (which typically lasts 8 years from initial General Availability).
Google's client libraries support legacy versions of Java runtimes with long term stable libraries that don't receive feature updates on a best efforts basis as it may not be possible to backport all patches.
Google provides updates on a best efforts basis to apps that continue to use Java 7, though apps might need to upgrade to current versions of the library that supports their JVM.
The latest versions and the supported Java versions are identified on
the individual GitHub repository github.com/GoogleAPIs/java-SERVICENAME
and on google-cloud-java.
This library follows Semantic Versioning.
Contributions to this library are always welcome and highly encouraged.
See CONTRIBUTING for more information how to get started.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Code of Conduct for more information.
Apache 2.0 - See LICENSE for more information.
| Java Version | Status |
|---|---|
| Java 8 | |
| Java 8 OSX | |
| Java 8 Windows | |
| Java 11 |
Java is a registered trademark of Oracle and/or its affiliates.
