Search in sources :

Example 1 with SpannerOptions

use of com.google.cloud.spanner.SpannerOptions in project java-docs-samples by GoogleCloudPlatform.

the class SpannerClient method connect.

private static void connect() throws IOException {
    if (INSTANCE_ID == null) {
        if (sc != null) {
            sc.log("environment variable SPANNER_INSTANCE need to be defined.");
        }
        return;
    }
    SpannerOptions options = SpannerOptions.newBuilder().build();
    PROJECT_ID = options.getProjectId();
    spanner = options.getService();
    databaseAdminClient = spanner.getDatabaseAdminClient();
}
Also used : SpannerOptions(com.google.cloud.spanner.SpannerOptions)

Example 2 with SpannerOptions

use of com.google.cloud.spanner.SpannerOptions in project java-docs-samples by GoogleCloudPlatform.

the class BatchSample method main.

/**
 * This example showcases how to create a batch client, partition a query, and concurrently read
 * from multiple partitions.
 */
public static void main(String[] args) throws InterruptedException {
    if (args.length != 2) {
        System.err.println("Usage: BatchSample <instance_id> <database_id>");
        return;
    }
    /*
     * CREATE TABLE Singers (
     *   SingerId   INT64 NOT NULL,
     *   FirstName  STRING(1024),
     *   LastName   STRING(1024),
     *   SingerInfo BYTES(MAX),
     * ) PRIMARY KEY (SingerId);
     */
    String instanceId = args[0];
    String databaseId = args[1];
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();
    // [START spanner_batch_client]
    int numThreads = Runtime.getRuntime().availableProcessors();
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    // Statistics
    int totalPartitions;
    AtomicInteger totalRecords = new AtomicInteger(0);
    try {
        BatchClient batchClient = spanner.getBatchClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
        final BatchReadOnlyTransaction txn = batchClient.batchReadOnlyTransaction(TimestampBound.strong());
        // A Partition object is serializable and can be used from a different process.
        List<Partition> partitions = txn.partitionQuery(PartitionOptions.getDefaultInstance(), Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"));
        totalPartitions = partitions.size();
        for (final Partition p : partitions) {
            executor.execute(() -> {
                try (ResultSet results = txn.execute(p)) {
                    while (results.next()) {
                        long singerId = results.getLong(0);
                        String firstName = results.getString(1);
                        String lastName = results.getString(2);
                        System.out.println("[" + singerId + "] " + firstName + " " + lastName);
                        totalRecords.getAndIncrement();
                    }
                }
            });
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        spanner.close();
    }
    double avgRecordsPerPartition = 0.0;
    if (totalPartitions != 0) {
        avgRecordsPerPartition = (double) totalRecords.get() / totalPartitions;
    }
    System.out.println("totalPartitions=" + totalPartitions);
    System.out.println("totalRecords=" + totalRecords);
    System.out.println("avgRecordsPerPartition=" + avgRecordsPerPartition);
// [END spanner_batch_client]
}
Also used : Partition(com.google.cloud.spanner.Partition) BatchClient(com.google.cloud.spanner.BatchClient) SpannerOptions(com.google.cloud.spanner.SpannerOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BatchReadOnlyTransaction(com.google.cloud.spanner.BatchReadOnlyTransaction) ExecutorService(java.util.concurrent.ExecutorService) ResultSet(com.google.cloud.spanner.ResultSet) Spanner(com.google.cloud.spanner.Spanner)

Example 3 with SpannerOptions

use of com.google.cloud.spanner.SpannerOptions in project java-docs-samples by GoogleCloudPlatform.

the class SpannerSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        printUsageAndExit();
    }
    // [START init_client]
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();
    try {
        String command = args[0];
        DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
        // [END init_client]
        // This will return the default project id based on the environment.
        String clientProject = spanner.getOptions().getProjectId();
        if (!db.getInstanceId().getProject().equals(clientProject)) {
            System.err.println("Invalid project specified. Project in the database id should match" + "the project name set in the environment variable GCLOUD_PROJECT. Expected: " + clientProject);
            printUsageAndExit();
        }
        // [START init_client]
        DatabaseClient dbClient = spanner.getDatabaseClient(db);
        DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
        // [END init_client]
        run(dbClient, dbAdminClient, command, db);
    } finally {
        spanner.close();
    }
    System.out.println("Closed client");
}
Also used : DatabaseClient(com.google.cloud.spanner.DatabaseClient) DatabaseAdminClient(com.google.cloud.spanner.DatabaseAdminClient) DatabaseId(com.google.cloud.spanner.DatabaseId) SpannerOptions(com.google.cloud.spanner.SpannerOptions) Spanner(com.google.cloud.spanner.Spanner)

Example 4 with SpannerOptions

use of com.google.cloud.spanner.SpannerOptions in project java-docs-samples by GoogleCloudPlatform.

the class TracingSample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: TracingSample <instance_id> <database_id>");
        return;
    }
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();
    // Installs a handler for /tracez page.
    ZPageHandlers.startHttpServerAndRegisterAll(8080);
    // Installs an exporter for stack driver traces.
    StackdriverExporter.createAndRegister();
    Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));
    // Installs an exporter for stack driver stats.
    StackdriverStatsExporter.createAndRegister();
    RpcViews.registerAllCumulativeViews();
    // Name of your instance & database.
    String instanceId = args[0];
    String databaseId = args[1];
    try {
        // Creates a database client
        DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
        // Queries the database
        try (Scope ss = Tracing.getTracer().spanBuilderWithExplicitParent(SAMPLE_SPAN, null).setSampler(Samplers.alwaysSample()).startScopedSpan()) {
            ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));
            System.out.println("\n\nResults:");
            // Prints the results
            while (resultSet.next()) {
                System.out.printf("%d\n\n", resultSet.getLong(0));
            }
        }
    } finally {
        // Closes the client which will free up the resources used
        spanner.close();
    }
}
Also used : DatabaseClient(com.google.cloud.spanner.DatabaseClient) Scope(io.opencensus.common.Scope) ResultSet(com.google.cloud.spanner.ResultSet) SpannerOptions(com.google.cloud.spanner.SpannerOptions) Spanner(com.google.cloud.spanner.Spanner)

Example 5 with SpannerOptions

use of com.google.cloud.spanner.SpannerOptions in project java-docs-samples by GoogleCloudPlatform.

the class SpannerSampleIT method setUp.

@Before
public void setUp() throws Exception {
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();
    dbClient = spanner.getDatabaseAdminClient();
    dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId);
    dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase());
}
Also used : SpannerOptions(com.google.cloud.spanner.SpannerOptions) Spanner(com.google.cloud.spanner.Spanner) Before(org.junit.Before)

Aggregations

SpannerOptions (com.google.cloud.spanner.SpannerOptions)19 Spanner (com.google.cloud.spanner.Spanner)13 DatabaseClient (com.google.cloud.spanner.DatabaseClient)6 ResultSet (com.google.cloud.spanner.ResultSet)4 Test (org.junit.Test)4 BatchClient (com.google.cloud.spanner.BatchClient)3 DatabaseAdminClient (com.google.cloud.spanner.DatabaseAdminClient)3 DatabaseId (com.google.cloud.spanner.DatabaseId)3 Builder (com.google.cloud.spanner.SpannerOptions.Builder)3 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)2 InstanceAdminClient (com.google.cloud.spanner.InstanceAdminClient)2 RetrySettings (com.google.api.gax.retrying.RetrySettings)1 ServerStreamingCallSettings (com.google.api.gax.rpc.ServerStreamingCallSettings)1 UnaryCallSettings (com.google.api.gax.rpc.UnaryCallSettings)1 BatchReadOnlyTransaction (com.google.cloud.spanner.BatchReadOnlyTransaction)1 InstanceConfig (com.google.cloud.spanner.InstanceConfig)1 Partition (com.google.cloud.spanner.Partition)1 CommitRequest (com.google.spanner.v1.CommitRequest)1 CommitResponse (com.google.spanner.v1.CommitResponse)1 ExecuteSqlRequest (com.google.spanner.v1.ExecuteSqlRequest)1