|
| 1 | +/* |
| 2 | + * Copyright 2022 Google Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.spanner; |
| 18 | + |
| 19 | +//[START spanner_postgresql_async_read_write_transaction] |
| 20 | +import com.google.api.core.ApiFuture; |
| 21 | +import com.google.api.core.ApiFutures; |
| 22 | +import com.google.cloud.spanner.AsyncRunner; |
| 23 | +import com.google.cloud.spanner.DatabaseClient; |
| 24 | +import com.google.cloud.spanner.DatabaseId; |
| 25 | +import com.google.cloud.spanner.Key; |
| 26 | +import com.google.cloud.spanner.Spanner; |
| 27 | +import com.google.cloud.spanner.SpannerExceptionFactory; |
| 28 | +import com.google.cloud.spanner.SpannerOptions; |
| 29 | +import com.google.cloud.spanner.Statement; |
| 30 | +import com.google.cloud.spanner.Struct; |
| 31 | +import com.google.common.collect.ImmutableList; |
| 32 | +import com.google.common.util.concurrent.MoreExecutors; |
| 33 | +import java.util.Arrays; |
| 34 | +import java.util.concurrent.ExecutionException; |
| 35 | +import java.util.concurrent.ExecutorService; |
| 36 | +import java.util.concurrent.Executors; |
| 37 | +import java.util.concurrent.TimeUnit; |
| 38 | +import java.util.concurrent.TimeoutException; |
| 39 | + |
| 40 | +class PgAsyncRunnerExample { |
| 41 | + |
| 42 | + static void asyncRunner() throws InterruptedException, ExecutionException, TimeoutException { |
| 43 | + // TODO(developer): Replace these variables before running the sample. |
| 44 | + String projectId = "my-project"; |
| 45 | + String instanceId = "my-instance"; |
| 46 | + String databaseId = "my-database"; |
| 47 | + |
| 48 | + try (Spanner spanner = |
| 49 | + SpannerOptions.newBuilder().setProjectId(projectId).build().getService()) { |
| 50 | + DatabaseClient client = |
| 51 | + spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId)); |
| 52 | + asyncRunner(client); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Execute a read/write transaction asynchronously. |
| 57 | + static void asyncRunner(DatabaseClient client) |
| 58 | + throws InterruptedException, ExecutionException, TimeoutException { |
| 59 | + ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 60 | + |
| 61 | + // Create an async transaction runner. |
| 62 | + AsyncRunner runner = client.runAsync(); |
| 63 | + // The transaction returns the total number of rows that were updated as a future array of |
| 64 | + // longs. |
| 65 | + ApiFuture<long[]> rowCounts = |
| 66 | + runner.runAsync( |
| 67 | + txn -> { |
| 68 | + // Transfer marketing budget from one album to another. We do it in a |
| 69 | + // transaction to ensure that the transfer is atomic. |
| 70 | + ApiFuture<Struct> album1BudgetFut = |
| 71 | + txn.readRowAsync("Albums", Key.of(1, 1), ImmutableList.of("MarketingBudget")); |
| 72 | + ApiFuture<Struct> album2BudgetFut = |
| 73 | + txn.readRowAsync("Albums", Key.of(2, 2), ImmutableList.of("MarketingBudget")); |
| 74 | + |
| 75 | + try { |
| 76 | + // Transaction will only be committed if this condition still holds at the |
| 77 | + // time of commit. Otherwise it will be aborted and the AsyncWork will be |
| 78 | + // rerun by the client library. |
| 79 | + long transfer = 200_000; |
| 80 | + if (album2BudgetFut.get().getLong(0) >= transfer) { |
| 81 | + long album1Budget = album1BudgetFut.get().getLong(0); |
| 82 | + long album2Budget = album2BudgetFut.get().getLong(0); |
| 83 | + |
| 84 | + album1Budget += transfer; |
| 85 | + album2Budget -= transfer; |
| 86 | + Statement updateStatement1 = |
| 87 | + Statement.newBuilder( |
| 88 | + "UPDATE Albums " |
| 89 | + + "SET MarketingBudget = $1 " |
| 90 | + + "WHERE SingerId = 1 and AlbumId = 1") |
| 91 | + .bind("p1") |
| 92 | + .to(album1Budget) |
| 93 | + .build(); |
| 94 | + Statement updateStatement2 = |
| 95 | + Statement.newBuilder( |
| 96 | + "UPDATE Albums " |
| 97 | + + "SET MarketingBudget = $1 " |
| 98 | + + "WHERE SingerId = 2 and AlbumId = 2") |
| 99 | + .bind("p1") |
| 100 | + .to(album2Budget) |
| 101 | + .build(); |
| 102 | + return txn.batchUpdateAsync( |
| 103 | + ImmutableList.of(updateStatement1, updateStatement2)); |
| 104 | + } else { |
| 105 | + return ApiFutures.immediateFuture(new long[] {0L, 0L}); |
| 106 | + } |
| 107 | + } catch (ExecutionException e) { |
| 108 | + throw SpannerExceptionFactory.newSpannerException(e.getCause()); |
| 109 | + } catch (InterruptedException e) { |
| 110 | + throw SpannerExceptionFactory.propagateInterrupt(e); |
| 111 | + } |
| 112 | + }, |
| 113 | + executor); |
| 114 | + |
| 115 | + ApiFuture<Long> totalUpdateCount = |
| 116 | + ApiFutures.transform( |
| 117 | + rowCounts, |
| 118 | + input -> Arrays.stream(input).sum(), |
| 119 | + MoreExecutors.directExecutor()); |
| 120 | + System.out.printf("%d records updated.%n", totalUpdateCount.get(30L, TimeUnit.SECONDS)); |
| 121 | + executor.shutdown(); |
| 122 | + } |
| 123 | +} |
| 124 | +//[END spanner_postgresql_async_read_write_transaction] |
0 commit comments