Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

googleapis/java-spanner

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Java idiomatic client forCloud Spanner.

MavenStability

Quickstart

If you are using Maven withBOM, add this to your pom.xml file:

<dependencyManagement>  <dependencies>    <dependency>      <groupId>com.google.cloud</groupId>      <artifactId>libraries-bom</artifactId>      <version>26.71.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.1</version></dependency>

If you are using Gradle 5.x or later, add this to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.72.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.103.0'

If you are using SBT, add this to your dependencies:

libraryDependencies+="com.google.cloud"%"google-cloud-spanner"%"6.103.0"

Authentication

See theAuthentication section in the base directory's README.

Authorization

The client application making API calls must be grantedauthorization scopes required for the desired Cloud Spanner APIs, and the authenticated principal must have theIAM role(s) required to access GCP resources using the Cloud Spanner API calls.

Getting Started

Prerequisites

You will need aGoogle Cloud Platform Console project with the Cloud SpannerAPI enabled.You will need toenable 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 byinstalling the Google Cloud Command Line Interface and running the following commands in command line:gcloud auth login andgcloud config set project [YOUR PROJECT ID].

Installation and setup

You'll need to obtain thegoogle-cloud-spanner library. See theQuickstart sectionto addgoogle-cloud-spanner as a dependency in your code.

About Cloud Spanner

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 theCloud Spanner client library docs to learn how touse this Cloud Spanner Client Library.

Calling Cloud Spanner

Here is a code snippet showing a simple usage example. Add the following importsat the top of your file:

importcom.google.cloud.spanner.DatabaseClient;importcom.google.cloud.spanner.DatabaseId;importcom.google.cloud.spanner.ResultSet;importcom.google.cloud.spanner.Spanner;importcom.google.cloud.spanner.SpannerOptions;importcom.google.cloud.spanner.Statement;

Then, to make a query to Spanner, use the following code:

// Instantiates a clientSpannerOptionsoptions =SpannerOptions.newBuilder().build();Spannerspanner =options.getService();Stringinstance ="my-instance";Stringdatabase ="my-database";try {// Creates a database clientDatabaseClientdbClient =spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(),instance,database));// Queries the databasetry (ResultSetresultSet =dbClient.singleUse().executeQuery(Statement.of("SELECT 1"))) {// Prints the resultswhile (resultSet.next()) {System.out.printf("%d\n",resultSet.getLong(0));    }  }}finally {// Closes the client which will free up the resources usedspanner.close();}

Complete source code

InDatabaseSelect.java we put together all the code shown above in a single program.

Session Pool

The Cloud Spanner client maintains a session pool, as sessions are expensive to create and areintended to be long-lived. The client automatically takes a session from the pool and uses thisexecuting queries and transactions.SeeSession Pool and Channel Pool Configurationfor in-depth background information about sessions and gRPC channels and how these are handled inthe Cloud Spanner Java client.

Metrics

Cloud Spanner client supportsclient-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 settingSPANNER_DISABLE_BUILTIN_METRICS totrue.

Note: Client-side metrics needsmonitoring.timeSeries.create IAM permission to export metrics data. Ask your administrator to grant your service account theMonitoring Metric Writer (roles/monitoring.metricWriter) IAM role on the project.

Traces

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.

SeeConfigure client-side tracing for more details on configuring traces.

OpenTelemetry Dependencies

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}'

OpenTelemetry Configuration

Note: Enabling OpenTelemetry traces will automatically disable OpenCensus traces.

// Enable OpenTelemetry tracesSpannerOptions.enableOpenTelemetryTraces();// Create a new tracer providerSdkTracerProvidersdkTracerProvider =SdkTracerProvider.builder()// Use Otlp exporter or any other exporter of your choice.      .addSpanProcessor(SimpleSpanProcessor.builder(OtlpGrpcSpanExporter          .builder().build()).build())          .build();OpenTelemetryopenTelemetry =OpenTelemetrySdk.builder()        .setTracerProvider(sdkTracerProvider)        .build()SpannerOptionsoptions =SpannerOptions.newBuilder()// Inject OpenTelemetry object via Spanner Options or register OpenTelmetry object as Global  .setOpenTelemetry(openTelemetry)  .build();Spannerspanner =options.getService();

OpenTelemetry SQL Statement Tracing

The OpenTelemetry traces that are generated by the Java client include any request and transactiontags that have been set. The traces can also include the SQL statements that are executed and thename of the thread that executes the statement. Enable this with theenableExtendedTracingoption:

SpannerOptions options = SpannerOptions.newBuilder()  .setOpenTelemetry(openTelemetry)  .setEnableExtendedTracing(true)  .build();

This option can also be enabled by setting the environment variableSPANNER_ENABLE_EXTENDED_TRACING=true.

OpenTelemetry API Tracing

You can enable tracing of each API call that the Spanner client executes with theenableApiTracingoption. 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 variableSPANNER_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.

End-to-end Tracing

In addition to client-side tracing, you can opt in forend-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 toConfigure end-to-end tracing to configure end-to-end tracing and to understand its attributes.

Note: End-to-end traces can only be exported toCloud Trace.

Instrument with OpenCensus

Note: OpenCensus project is deprecated. SeeSunsetting OpenCensus.We recommend migrating to OpenTelemetry, the successor project.

Migrate from OpenCensus to OpenTelemetry

Using theOpenTelemetry OpenCensus Bridge, you can immediately begin exporting your metrics and traces with OpenTelemetry.

Disable OpenCensus metrics

Disable OpenCensus metrics for Spanner by including the following code if you still possess OpenCensus dependencies and exporter.

SpannerOptions.disableOpenCensusMetrics();

Disable OpenCensus traces

Enabling OpenTelemetry traces for Spanner will automatically disable OpenCensus traces.

SpannerOptions.enableOpenTelemetryTraces();

Remove OpenCensus Dependencies and Code

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 configuredhere
  • Remove SpannerRPCViews reference which were configuredhere
  • Remove the OpenCensus dependencies which were addedhere

Update your Dashboards and Alerts

Update your dashboards and alerts to reflect below changes

  • Metrics name :cloud.google.com/java prefix has been removed from OpenTelemery metrics and instead has been added as Instrumenation Scope.
  • Metrics namespace : OpenTelmetry exporters usesworkload.googleapis.com namespace opposed tocustom.googleapis.com with OpenCensus.

Samples

Samples are in thesamples/ directory.

SampleSource CodeTry it
Add And Drop Database Rolesource codeOpen in Cloud Shell
Add Json Column Samplesource codeOpen in Cloud Shell
Add Jsonb Column Samplesource codeOpen in Cloud Shell
Add Numeric Column Samplesource codeOpen in Cloud Shell
Add Proto Column Samplesource codeOpen in Cloud Shell
Alter Sequence Samplesource codeOpen in Cloud Shell
Alter Table With Foreign Key Delete Cascade Samplesource codeOpen in Cloud Shell
Async Dml Examplesource codeOpen in Cloud Shell
Async Query Examplesource codeOpen in Cloud Shell
Async Query To List Async Examplesource codeOpen in Cloud Shell
Async Read Examplesource codeOpen in Cloud Shell
Async Read Only Transaction Examplesource codeOpen in Cloud Shell
Async Read Row Examplesource codeOpen in Cloud Shell
Async Read Using Index Examplesource codeOpen in Cloud Shell
Async Runner Examplesource codeOpen in Cloud Shell
Async Transaction Manager Examplesource codeOpen in Cloud Shell
Batch Samplesource codeOpen in Cloud Shell
Batch Write At Least Once Samplesource codeOpen in Cloud Shell
Change Streams Txn Exclusion Samplesource codeOpen in Cloud Shell
Copy Backup Samplesource codeOpen in Cloud Shell
Copy Backup With Multi Region Encryption Keysource codeOpen in Cloud Shell
Create Backup With Encryption Keysource codeOpen in Cloud Shell
Create Backup With Multi Region Encryption Keysource codeOpen in Cloud Shell
Create Database With Default Leader Samplesource codeOpen in Cloud Shell
Create Database With Encryption Keysource codeOpen in Cloud Shell
Create Database With Multi Region Encryption Keysource codeOpen in Cloud Shell
Create Database With Version Retention Period Samplesource codeOpen in Cloud Shell
Create Full Backup Schedule Samplesource codeOpen in Cloud Shell
Create Incremental Backup Schedule Samplesource codeOpen in Cloud Shell
Create Instance Config Samplesource codeOpen in Cloud Shell
Create Instance Examplesource codeOpen in Cloud Shell
Create Instance Partition Samplesource codeOpen in Cloud Shell
Create Instance With Asymmetric Autoscaling Config Examplesource codeOpen in Cloud Shell
Create Instance With Autoscaling Config Examplesource codeOpen in Cloud Shell
Create Instance With Processing Units Examplesource codeOpen in Cloud Shell
Create Instance Without Default Backup Schedules Examplesource codeOpen in Cloud Shell
Create Sequence Samplesource codeOpen in Cloud Shell
Create Table With Foreign Key Delete Cascade Samplesource codeOpen in Cloud Shell
Custom Timeout And Retry Settings Examplesource codeOpen in Cloud Shell
Database Add Split Points Samplesource codeOpen in Cloud Shell
Delete Backup Schedule Samplesource codeOpen in Cloud Shell
Delete Instance Config Samplesource codeOpen in Cloud Shell
Delete Using Dml Returning Samplesource codeOpen in Cloud Shell
Directed Read Samplesource codeOpen in Cloud Shell
Drop Foreign Key Constraint Delete Cascade Samplesource codeOpen in Cloud Shell
Drop Sequence Samplesource codeOpen in Cloud Shell
Enable Fine Grained Accesssource codeOpen in Cloud Shell
Get Backup Schedule Samplesource codeOpen in Cloud Shell
Get Commit Stats Samplesource codeOpen in Cloud Shell
Get Database Ddl Samplesource codeOpen in Cloud Shell
Get Instance Config Samplesource codeOpen in Cloud Shell
Insert Using Dml Returning Samplesource codeOpen in Cloud Shell
Last Statement Samplesource codeOpen in Cloud Shell
List Backup Schedules Samplesource codeOpen in Cloud Shell
List Database Rolessource codeOpen in Cloud Shell
List Databases Samplesource codeOpen in Cloud Shell
List Instance Config Operations Samplesource codeOpen in Cloud Shell
List Instance Configs Samplesource codeOpen in Cloud Shell
Pg Alter Sequence Samplesource codeOpen in Cloud Shell
Pg Async Query To List Async Examplesource codeOpen in Cloud Shell
Pg Async Runner Examplesource codeOpen in Cloud Shell
Pg Async Transaction Manager Examplesource codeOpen in Cloud Shell
Pg Batch Dml Samplesource codeOpen in Cloud Shell
Pg Case Sensitivity Samplesource codeOpen in Cloud Shell
Pg Create Sequence Samplesource codeOpen in Cloud Shell
Pg Delete Using Dml Returning Samplesource codeOpen in Cloud Shell
Pg Drop Sequence Samplesource codeOpen in Cloud Shell
Pg Insert Using Dml Returning Samplesource codeOpen in Cloud Shell
Pg Interleaved Table Samplesource codeOpen in Cloud Shell
Pg Last Statement Samplesource codeOpen in Cloud Shell
Pg Partitioned Dml Samplesource codeOpen in Cloud Shell
Pg Query With Numeric Parameter Samplesource codeOpen in Cloud Shell
Pg Spanner Samplesource codeOpen in Cloud Shell
Pg Update Using Dml Returning Samplesource codeOpen in Cloud Shell
Query Information Schema Database Options Samplesource codeOpen in Cloud Shell
Query With Json Parameter Samplesource codeOpen in Cloud Shell
Query With Jsonb Parameter Samplesource codeOpen in Cloud Shell
Query With Numeric Parameter Samplesource codeOpen in Cloud Shell
Query With Proto Parameter Samplesource codeOpen in Cloud Shell
Quickstart Samplesource codeOpen in Cloud Shell
Read Data With Database Rolesource codeOpen in Cloud Shell
Restore Backup With Encryption Keysource codeOpen in Cloud Shell
Restore Backup With Multi Region Encryption Keysource codeOpen in Cloud Shell
Set Max Commit Delay Samplesource codeOpen in Cloud Shell
Singer Protosource codeOpen in Cloud Shell
Spanner Graph Samplesource codeOpen in Cloud Shell
Spanner Samplesource codeOpen in Cloud Shell
Statement Timeout Examplesource codeOpen in Cloud Shell
Tag Samplesource codeOpen in Cloud Shell
Tracing Samplesource codeOpen in Cloud Shell
Transaction Timeout Examplesource codeOpen in Cloud Shell
Unnamed Parameters Examplesource codeOpen in Cloud Shell
Update Backup Schedule Samplesource codeOpen in Cloud Shell
Update Database Samplesource codeOpen in Cloud Shell
Update Database With Default Leader Samplesource codeOpen in Cloud Shell
Update Instance Config Samplesource codeOpen in Cloud Shell
Update Instance Default Backup Schedule Type Examplesource codeOpen in Cloud Shell
Update Instance Examplesource codeOpen in Cloud Shell
Update Json Data Samplesource codeOpen in Cloud Shell
Update Jsonb Data Samplesource codeOpen in Cloud Shell
Update Numeric Data Samplesource codeOpen in Cloud Shell
Update Proto Data Samplesource codeOpen in Cloud Shell
Update Proto Data Sample Using Dmlsource codeOpen in Cloud Shell
Update Using Dml Returning Samplesource codeOpen in Cloud Shell
Add And Drop Database Rolesource codeOpen in Cloud Shell
Add Json Column Samplesource codeOpen in Cloud Shell
Add Jsonb Column Samplesource codeOpen in Cloud Shell
Add Numeric Column Samplesource codeOpen in Cloud Shell
Alter Sequence Samplesource codeOpen in Cloud Shell
Alter Table With Foreign Key Delete Cascade Samplesource codeOpen in Cloud Shell
Copy Backup Samplesource codeOpen in Cloud Shell
Create Backup With Encryption Keysource codeOpen in Cloud Shell
Create Database With Default Leader Samplesource codeOpen in Cloud Shell
Create Database With Encryption Keysource codeOpen in Cloud Shell
Create Database With Version Retention Period Samplesource codeOpen in Cloud Shell
Create Instance Config Samplesource codeOpen in Cloud Shell
Create Instance Examplesource codeOpen in Cloud Shell
Create Instance With Autoscaling Config Examplesource codeOpen in Cloud Shell
Create Instance With Processing Units Examplesource codeOpen in Cloud Shell
Create Sequence Samplesource codeOpen in Cloud Shell
Create Table With Foreign Key Delete Cascade Samplesource codeOpen in Cloud Shell
Delete Instance Config Samplesource codeOpen in Cloud Shell
Drop Foreign Key Constraint Delete Cascade Samplesource codeOpen in Cloud Shell
Drop Sequence Samplesource codeOpen in Cloud Shell
Enable Fine Grained Accesssource codeOpen in Cloud Shell
Get Database Ddl Samplesource codeOpen in Cloud Shell
Get Instance Config Samplesource codeOpen in Cloud Shell
List Database Rolessource codeOpen in Cloud Shell
List Databases Samplesource codeOpen in Cloud Shell
List Instance Config Operations Samplesource codeOpen in Cloud Shell
List Instance Configs Samplesource codeOpen in Cloud Shell
Pg Alter Sequence Samplesource codeOpen in Cloud Shell
Pg Case Sensitivity Samplesource codeOpen in Cloud Shell
Pg Create Sequence Samplesource codeOpen in Cloud Shell
Pg Drop Sequence Samplesource codeOpen in Cloud Shell
Pg Interleaved Table Samplesource codeOpen in Cloud Shell
Pg Spanner Samplesource codeOpen in Cloud Shell
Restore Backup With Encryption Keysource codeOpen in Cloud Shell
Spanner Samplesource codeOpen in Cloud Shell
Update Database Samplesource codeOpen in Cloud Shell
Update Database With Default Leader Samplesource codeOpen in Cloud Shell
Update Instance Config Samplesource codeOpen in Cloud Shell

Troubleshooting

To get help, follow the instructions in theshared Troubleshooting document.

Transport

Cloud Spanner uses gRPC for the transport layer.

Supported Java Versions

Java 8 or above is required for using this client.

Google's Java client libraries,Google Cloud Client LibrariesandGoogle Cloud API Libraries,follow theOracle Java SE support roadmap(see the Oracle Java SE Product Releases section).

For new development

In general, new feature development occurs with support for the lowest JavaLTS version covered by Oracle's Premier Support (which typically lasts 5 yearsfrom initial General Availability). If the minimum required JVM for a givenlibrary is changed, it is accompanied by asemver major release.

Java 11 and (in September 2021) Java 17 are the best choices for newdevelopment.

Keeping production systems current

Google tests its client libraries with all current LTS versions covered byOracle's Extended Support (which typically lasts 8 years from initialGeneral Availability).

Legacy support

Google's client libraries support legacy versions of Java runtimes with longterm stable libraries that don't receive feature updates on a best efforts basisas it may not be possible to backport all patches.

Google provides updates on a best efforts basis to apps that continue to useJava 7, though apps might need to upgrade to current versions of the librarythat supports their JVM.

Where to find specific information

The latest versions and the supported Java versions are identified onthe individual GitHub repositorygithub.com/GoogleAPIs/java-SERVICENAMEand ongoogle-cloud-java.

Versioning

This library followsSemantic Versioning.

Contributing

Contributions to this library are always welcome and highly encouraged.

SeeCONTRIBUTING for more information how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating inthis project you agree to abide by its terms. SeeCode of Conduct for moreinformation.

License

Apache 2.0 - SeeLICENSE for more information.

CI Status

Java VersionStatus
Java 8Kokoro CI
Java 8 OSXKokoro CI
Java 8 WindowsKokoro CI
Java 11Kokoro CI

Java is a registered trademark of Oracle and/or its affiliates.

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors143

Languages


[8]ページ先頭

©2009-2025 Movatter.jp