קריאה מודרכת

בדף הזה מוסבר על קריאות מונחות ב-Spanner ואיך משתמשים בהן.

קריאות מופנות ב-Spanner מאפשרות גמישות בהפניית טרנזקציות לקריאה בלבד וקריאות בודדות לסוג רפליקה או לאזור ספציפיים במסגרת הגדרת מופע של שני אזורים או של מספר אזורים, או במסגרת הגדרה אזורית בהתאמה אישית עם אזורים אופציונליים לקריאה בלבד.

יתרונות

היתרונות של קריאות מופנות:

  • שליטה רבה יותר בעומסי עבודה של איזון עומסים בכמה אזורים כדי להשיג ניצול אחיד יותר של CPU ולמנוע הקצאת יתר של מופעי Spanner.
  • הפעלת בידוד עומסי עבודה. אתם יכולים להפנות את עומסי העבודה של ניתוח הנתונים וקריאות של סנכרון שינויים בזרמי נתונים לשכפולים ספציפיים של Spanner כדי למזער את ההשפעה על עומסי עבודה של טרנזקציות שפועלים באותו מסד נתונים של Spanner.

פעולות נתמכות בשאילתות

פעולות של שאילתות האם יש תמיכה בקריאה מכוונת?
קריאה בעבר כן
קריאה חזקה כן
עסקת קריאה-כתיבה לא

אין תמיכה בקריאות ישירות בטרנזקציות של קריאה וכתיבה ובסוגים של עדכונים בכמות גדולה כמו חלוקה למחיצות של DML. הסיבה לכך היא שעסקאות קריאה-כתיבה צריכות לעבור עיבוד באזור הראשי. אם משתמשים בקריאות ישירות בעסקת קריאה-כתיבה, העסקה נכשלת עם שגיאת BAD_REQUEST.

מגבלות

יש הגבלות על קריאות ישירות ב-Spanner:

לפני שמתחילים

לפני שמשתמשים בקריאות מונחות, כדאי לשים לב לנקודות הבאות:

  • יכול להיות שיהיה לאפליקציה זמן אחזור נוסף אם אתם מעבירים קריאות לרפליקה או לאזור אחרים, ולא לאלה שהכי קרובים לאפליקציה.
  • אפשר לנתב את התנועה לפי:
    • שם האזור (לדוגמה: us-central1).
    • סוג הרפליקה (הערכים האפשריים: READ_ONLY ו-READ_WRITE).
  • אפשרות המעבר האוטומטי לגיבוי בקריאות מופנות מופעלת כברירת מחדל. כשהאפשרות של מעבר אוטומטי לגיבוי מופעלת וכל העותקים המשוכפלים שצוינו לא זמינים או לא תקינים, Spanner מעביר את הבקשות לעותק משוכפל שלא נמצא ברשימה includeReplicas. אם משביתים את האפשרות של מעבר אוטומטי לגיבוי וכל העותקים המשוכפלים שצוינו לא זמינים או לא תקינים, בקשת הקריאה המכוונת נכשלת.

פרמטרים של קריאה מכוונת

אם אתם משתמשים ב-API ל-REST או ל-RPC כדי לבצע קריאות ממוקדות, אתם צריכים להגדיר את השדות האלה בפרמטר directedReadOptions. אפשר לכלול רק אחד מהתגים includeReplicas או excludeReplicas, ולא את שניהם.

  • includeReplicas: מכיל קבוצה חוזרת של replicaSelections. הרשימה הזו מציינת את הסדר שבו צריך להתייחס לקריאות ישירות לאזורים ספציפיים או לסוגי העתקים. אפשר לציין עד 10 includeReplicas.

    • replicaSelections: מורכב מ-location או משכפול type שמשרת את בקשת הקריאות המכוונות. אם אתם משתמשים ב-includeReplicas, אתם צריכים לספק לפחות אחד מהפרטים של השדות הבאים:

      • location: המיקום שבו מוגשת בקשת הקריאה המכוונת. המיקום חייב להיות אחד מהאזורים בהגדרת שני האזורים או מספר האזורים של מסד הנתונים. אם המיקום לא נמצא באחד מהאזורים בהגדרה של שני אזורים או של מספר אזורים במסד הנתונים, הבקשות לא ינותבו כמצופה. במקום זאת, הם מוגשים מהאזור הקרוב ביותר. לדוגמה, אפשר להפנות קריאות למיקום us-central1 במסד נתונים בהגדרת מופע של מספר אזורים nam6.

        אפשר גם לציין את הפרמטר location עם מחרוזת מילולית leader או non-leader. אם מזינים את הערך leader, בקשות מופנות ב-Spanner אל הרפליקה הראשית של מסד הנתונים. לעומת זאת, אם תזינו את הערך non-leader, ‏ Spanner יבצע את הבקשה ברפליקה הקרובה ביותר שאינה רפליקת הלידר.

      • type: סוג הרפליקה שמשרתת את בקשת הקריאה המכוונת. הסוגים האפשריים כוללים READ_WRITE ו-READ_ONLY.

    • autoFailoverDisabled: כברירת מחדל, הערך הזה מוגדר כ-False, כלומר מופעל מעבר גיבוי אוטומטי. כשהאפשרות של מעבר אוטומטי לגיבוי מופעלת, וכל העותקים המשוכפלים שצוינו לא זמינים או לא תקינים, Spanner מעביר את הבקשות לעותק משוכפל שלא מופיע ברשימה includeReplicas. אם משביתים את האפשרות של מעבר אוטומטי לגיבוי וכל העותקים המשוכפלים שצוינו לא זמינים או לא תקינים, בקשת הקריאה המכוונת נכשלת. הערכים האפשריים כוללים TRUE להשבתה ו-FALSE להפעלה.

  • excludeReplicas: מכיל קבוצה חוזרת של replicaSelections שמוחרגת מבקשות להצגת מודעות. מערכת Spanner לא מעבירה בקשות לרפליקות ברשימה הזו.

    • replicaSelections: המיקום או סוג הרפליקה שמוחרגים מהצגת הבקשה לקריאות מופנות. אם אתם משתמשים ב-excludeReplicas, אתם צריכים לספק לפחות אחד מהשדות הבאים:
      • location: המיקום שמוחרג מהצגת הבקשה לקריאות ישירות.
      • type: סוג הרפליקה שמוחרג מהצגת הבקשה של קריאות מופנות. הסוגים האפשריים כוללים READ_WRITE ו-READ_ONLY.

כדי לראות דוגמה לגוף של בקשת REST, לוחצים על הכרטיסייה REST בקטע שימוש בקריאות מופנות.

שימוש בהקראה מודרכת

אתם יכולים להשתמש בספריות הלקוח של Spanner ובממשקי API ל-REST ול-RPC כדי לבצע קריאות ממוקדות.

ספריות לקוח

C++‎

void DirectedRead(std::string const& project_id, std::string const& instance_id,
                  std::string const& database_id) {
  namespace spanner = ::google::cloud::spanner;

  // Create a client with a DirectedReadOption.
  auto client = spanner::Client(
      spanner::MakeConnection(
          spanner::Database(project_id, instance_id, database_id)),
      google::cloud::Options{}.set<spanner::DirectedReadOption>(
          spanner::ExcludeReplicas({spanner::ReplicaSelection("us-east4")})));

  spanner::SqlStatement select(
      "SELECT SingerId, AlbumId, AlbumTitle FROM Albums");
  using RowType = std::tuple<std::int64_t, std::int64_t, std::string>;

  // A DirectedReadOption on the operation will override the option set
  // at the client level.
  auto rows = client.ExecuteQuery(
      std::move(select),
      google::cloud::Options{}.set<spanner::DirectedReadOption>(
          spanner::IncludeReplicas(
              {spanner::ReplicaSelection(spanner::ReplicaType::kReadWrite)},
              /*auto_failover_disabled=*/true)));
  for (auto& row : spanner::StreamOf<RowType>(rows)) {
    if (!row) throw std::move(row).status();
    std::cout << "SingerId: " << std::get<0>(*row)
              << " AlbumId: " << std::get<1>(*row)
              << " AlbumTitle: " << std::get<2>(*row) << "\n";
  }
  std::cout << "Read completed for [spanner_directed_read]\n";
}

C#‎


using Google.Cloud.Spanner.Data;
using Google.Cloud.Spanner.V1;
using System.Collections.Generic;
using System.Threading.Tasks;

public class DirectedReadsAsyncSample
{
    public class Album
    {
        public int SingerId { get; set; }
        public int AlbumId { get; set; }
        public string AlbumTitle { get; set; }
    }

    public async Task<List<Album>> DirectedReadsAsync(string projectId, string instanceId, string databaseId)
    {
        string connectionString = $"Data Source=projects/{projectId}/instances/{instanceId}/databases/{databaseId}";
        using var connection = new SpannerConnection(connectionString);

        using var cmd = connection.CreateSelectCommand("SELECT SingerId, AlbumId, AlbumTitle FROM Albums");
        // Set directed read options on a query or read command.
        cmd.DirectedReadOptions = new DirectedReadOptions
        {
            IncludeReplicas = new DirectedReadOptions.Types.IncludeReplicas
            {
                AutoFailoverDisabled = true,
                ReplicaSelections =
                {
                    new DirectedReadOptions.Types.ReplicaSelection
                    {
                        Location = "us-central1",
                        Type = DirectedReadOptions.Types.ReplicaSelection.Types.Type.ReadOnly
                    }
                }
            }
        };

        var albums = new List<Album>();
        using var reader = await cmd.ExecuteReaderAsync();
        while (await reader.ReadAsync())
        {
            albums.Add(new Album
            {
                AlbumId = reader.GetFieldValue<int>("AlbumId"),
                SingerId = reader.GetFieldValue<int>("SingerId"),
                AlbumTitle = reader.GetFieldValue<string>("AlbumTitle")
            });
        }
        return albums;
    }
}

המשך


import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/spanner"
	sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
	"google.golang.org/api/iterator"
)

//	Shows how to run a query with directed read options.
//	Only one of ExcludeReplicas or IncludeReplicas can be set
//	Each accepts a list of ReplicaSelections which contains Location and Type
//	* `location` - The location must be one of the regions within the
//	multi-region configuration of your database.
//	* `type` - The type of the replica
//	Some examples of using replica_selectors are:
//	* `location:us-east1` --> The "us-east1" replica(s) of any available type
//		will be used to process the request.
//	* `type:READ_ONLY`    --> The "READ_ONLY" type replica(s) in nearest
//	available location will be used to process the
//	request.
//	* `location:us-east1 type:READ_ONLY` --> The "READ_ONLY" type replica(s)
//	in location "us-east1" will be used to process the request.
//		IncludeReplicas also contains an option for AutoFailoverDisabled which when set
//	Spanner will not route requests to a replica outside the
//	IncludeReplicas list when all the specified replicas are unavailable
//	or unhealthy. The default value is `false`

func directedReadOptions(w io.Writer, db string) error {
	// db = `projects/<project>/instances/<instance-id>/database/<database-id>`
	ctx := context.Background()
	directedReadOptionsForClient := &sppb.DirectedReadOptions{
		Replicas: &sppb.DirectedReadOptions_ExcludeReplicas_{
			ExcludeReplicas: &sppb.DirectedReadOptions_ExcludeReplicas{
				ReplicaSelections: []*sppb.DirectedReadOptions_ReplicaSelection{
					{
						Location: "us-east4",
					},
				},
			},
		},
	}
	// DirectedReadOptions can be set at client level and will be used in all read-only transaction requests
	client, err := spanner.NewClientWithConfig(ctx, db, spanner.ClientConfig{DirectedReadOptions: directedReadOptionsForClient})
	if err != nil {
		return err
	}
	defer client.Close()

	// DirectedReadOptions set at Request level will override the options set at Client level.
	directedReadOptionsForRequest := &sppb.DirectedReadOptions{
		Replicas: &sppb.DirectedReadOptions_IncludeReplicas_{
			IncludeReplicas: &sppb.DirectedReadOptions_IncludeReplicas{
				ReplicaSelections: []*sppb.DirectedReadOptions_ReplicaSelection{
					{
						Type: sppb.DirectedReadOptions_ReplicaSelection_READ_ONLY,
					},
				},
				AutoFailoverDisabled: true,
			},
		},
	}

	statement := spanner.Statement{SQL: `SELECT SingerId, AlbumId, AlbumTitle FROM Albums`}
	// // Read rows while passing directedReadOptions directly to the query.
	iter := client.Single().QueryWithOptions(ctx, statement, spanner.QueryOptions{DirectedReadOptions: directedReadOptionsForRequest})
	defer iter.Stop()
	for {
		row, err := iter.Next()
		if err == iterator.Done {
			return nil
		}
		if err != nil {
			return err
		}
		var singerID, albumID int64
		var albumTitle string
		if err := row.Columns(&singerID, &albumID, &albumTitle); err != nil {
			return err
		}
		fmt.Fprintf(w, "%d %d %s\n", singerID, albumID, albumTitle)
	}
}

Java

import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Options;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.spanner.v1.DirectedReadOptions;
import com.google.spanner.v1.DirectedReadOptions.ExcludeReplicas;
import com.google.spanner.v1.DirectedReadOptions.IncludeReplicas;
import com.google.spanner.v1.DirectedReadOptions.ReplicaSelection;

public class DirectedReadSample {
  static void directedRead() {
    // TODO(developer): Replace these variables before running the sample.
    final String projectId = "my-project";
    final String instanceId = "my-instance";
    final String databaseId = "my-database";
    directedRead(projectId, instanceId, databaseId);
  }

  static void directedRead(String projectId, String instanceId, String databaseId) {
    // Only one of excludeReplicas or includeReplicas can be set
    // Each accepts a list of replicaSelections which contains location and type
    //   * `location` - The location must be one of the regions within the
    //      multi-region configuration of your database.
    //   * `type` - The type of the replica
    // Some examples of using replicaSelectors are:
    //   * `location:us-east1` --> The "us-east1" replica(s) of any available type
    //                             will be used to process the request.
    //   * `type:READ_ONLY`    --> The "READ_ONLY" type replica(s) in nearest
    // .                            available location will be used to process the
    //                             request.
    //   * `location:us-east1 type:READ_ONLY` --> The "READ_ONLY" type replica(s)
    //                          in location "us-east1" will be used to process
    //                          the request.
    //  includeReplicas also contains an option called autoFailoverDisabled, which when set to true
    //  will instruct Spanner to not route requests to a replica outside the
    //  includeReplicas list when all the specified replicas are unavailable
    //  or unhealthy. Default value is `false`.
    final DirectedReadOptions directedReadOptionsForClient =
        DirectedReadOptions.newBuilder()
            .setExcludeReplicas(
                ExcludeReplicas.newBuilder()
                    .addReplicaSelections(
                        ReplicaSelection.newBuilder().setLocation("us-east4").build())
                    .build())
            .build();

    // You can set default `DirectedReadOptions` for a Spanner client. These options will be applied
    // to all read-only transactions that are executed by this client, unless specific
    // DirectedReadOptions are set for a query.
    // Directed read can only be used for read-only transactions. The default options will be
    // ignored for any read/write transaction that the client executes.
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .setDirectedReadOptions(directedReadOptionsForClient)
            .build()
            .getService()) {
      final DatabaseClient dbClient =
          spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId));

      // DirectedReadOptions at request level will override the options set at
      // client level (through SpannerOptions).
      final DirectedReadOptions directedReadOptionsForRequest =
          DirectedReadOptions.newBuilder()
              .setIncludeReplicas(
                  IncludeReplicas.newBuilder()
                      .addReplicaSelections(
                          ReplicaSelection.newBuilder()
                              .setType(ReplicaSelection.Type.READ_WRITE)
                              .build())
                      .setAutoFailoverDisabled(true)
                      .build())
              .build();

      // Read rows while passing DirectedReadOptions directly to the query.
      try (ResultSet rs =
          dbClient
              .singleUse()
              .executeQuery(
                  Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"),
                  Options.directedRead(directedReadOptionsForRequest))) {
        while (rs.next()) {
          System.out.printf(
              "SingerId: %d, AlbumId: %d, AlbumTitle: %s\n",
              rs.getLong(0), rs.getLong(1), rs.getString(2));
        }
        System.out.println("Successfully executed read-only transaction with directedReadOptions");
      }
    }
  }
}

Node.js

// Imports the Google Cloud Spanner client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Only one of excludeReplicas or includeReplicas can be set
// Each accepts a list of replicaSelections which contains location and type
//   * `location` - The location must be one of the regions within the
//      multi-region configuration of your database.
//   * `type` - The type of the replica
// Some examples of using replicaSelectors are:
//   * `location:us-east1` --> The "us-east1" replica(s) of any available type
//                             will be used to process the request.
//   * `type:READ_ONLY`    --> The "READ_ONLY" type replica(s) in nearest
//.                            available location will be used to process the
//                             request.
//   * `location:us-east1 type:READ_ONLY` --> The "READ_ONLY" type replica(s)
//                          in location "us-east1" will be used to process
//                          the request.
//  includeReplicas also contains an option for autoFailover which when set
//  Spanner will not route requests to a replica outside the
//  includeReplicas list when all the specified replicas are unavailable
//  or unhealthy. The default value is `false`
const directedReadOptionsForClient = {
  excludeReplicas: {
    replicaSelections: [
      {
        location: 'us-east4',
      },
    ],
  },
};

// Instantiates a client with directedReadOptions
const spanner = new Spanner({
  projectId: projectId,
  directedReadOptions: directedReadOptionsForClient,
});

async function spannerDirectedReads() {
  // Gets a reference to a Cloud Spanner instance and backup
  const instance = spanner.instance(instanceId);
  const database = instance.database(databaseId);
  const directedReadOptionsForRequest = {
    includeReplicas: {
      replicaSelections: [
        {
          type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection
            .Type.READ_ONLY,
        },
      ],
      autoFailoverDisabled: true,
    },
  };

  await database.getSnapshot(async (err, transaction) => {
    if (err) {
      console.error(err);
      return;
    }
    try {
      // Read rows while passing directedReadOptions directly to the query.
      // These will override the options passed at Client level.
      const [rows] = await transaction.run({
        sql: 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',
        directedReadOptions: directedReadOptionsForRequest,
      });
      rows.forEach(row => {
        const json = row.toJSON();
        console.log(
          `SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`,
        );
      });
      console.log(
        'Successfully executed read-only transaction with directedReadOptions',
      );
    } catch (err) {
      console.error('ERROR:', err);
    } finally {
      transaction.end();
      // Close the database when finished.
      await database.close();
    }
  });
}
spannerDirectedReads();

PHP

use Google\Cloud\Spanner\SpannerClient;
use Google\Cloud\Spanner\V1\DirectedReadOptions\ReplicaSelection\Type as ReplicaType;

/**
 * Queries sample data from the database with directed read options.
 * Example:
 * ```
 * directed_read($instanceId, $databaseId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 * @param string $databaseId The Spanner database ID.
 */
function directed_read(string $instanceId, string $databaseId): void
{
    $directedReadOptionsForClient = [
        'directedReadOptions' => [
            'excludeReplicas' => [
                'replicaSelections' => [
                    [
                        'location' => 'us-east4'
                    ]
                ]
            ]
        ]
    ];

    $directedReadOptionsForRequest = [
        'directedReadOptions' => [
            'includeReplicas' => [
                'replicaSelections' => [
                    [
                        'type' => ReplicaType::READ_WRITE
                    ]
                ],
                'autoFailoverDisabled' => true
            ]
        ]
    ];

    $spanner = new SpannerClient($directedReadOptionsForClient);
    $instance = $spanner->instance($instanceId);
    $database = $instance->database($databaseId);
    $snapshot = $database->snapshot();

    // directedReadOptions at Request level will override the options set at
    // Client level
    $results = $snapshot->execute(
        'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',
        $directedReadOptionsForRequest
    );

    foreach ($results as $row) {
        printf('SingerId: %s, AlbumId: %s, AlbumTitle: %s' . PHP_EOL,
            $row['SingerId'], $row['AlbumId'], $row['AlbumTitle']);
    }
}

Python

# instance_id = "your-spanner-instance"
# database_id = "your-spanner-db-id"

directed_read_options_for_client = {
    "exclude_replicas": {
        "replica_selections": [
            {
                "location": "us-east4",
            },
        ],
    },
}

# directed_read_options can be set at client level and will be used in all
# read-only transaction requests
spanner_client = spanner.Client(
    directed_read_options=directed_read_options_for_client
)
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)

directed_read_options_for_request = {
    "include_replicas": {
        "replica_selections": [
            {
                "type_": DirectedReadOptions.ReplicaSelection.Type.READ_ONLY,
            },
        ],
        "auto_failover_disabled": True,
    },
}

with database.snapshot() as snapshot:
    # Read rows while passing directed_read_options directly to the query.
    # These will override the options passed at Client level.
    results = snapshot.execute_sql(
        "SELECT SingerId, AlbumId, AlbumTitle FROM Albums",
        directed_read_options=directed_read_options_for_request,
    )

    for row in results:
        print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row))

Ruby

require "google/cloud/spanner"

##
# This is a snippet for showcasing how to pass in directed read options.
#
# @param project_id  [String] The ID of the Google Cloud project.
# @param instance_id [String] The ID of the spanner instance.
# @param database_id [String] The ID of the database.
#
def spanner_directed_read project_id:, instance_id:, database_id:
  # Only one of exclude_replicas or include_replicas can be set.
  # Each accepts a list of replica_selections which contains location and type
  #   * `location` - The location must be one of the regions within the
  #      multi-region configuration of your database.
  #   * `type` - The type of the replica
  # Some examples of using replicaSelectors are:
  #   * `location:us-east1` --> The "us-east1" replica(s) of any available type
  #                             will be used to process the request.
  #   * `type:READ_ONLY`    --> The "READ_ONLY" type replica(s) in the nearest
  # .                            available location will be used to process the
  #                             request.
  #   * `location:us-east1 type:READ_ONLY` --> The "READ_ONLY" type replica(s)
  #                          in location "us-east1" will be used to process
  #                          the request.
  #  include_replicas also contains an option for auto_failover_disabled. If set
  #  Spanner will not route requests to a replica outside the
  #  include_replicas list even if all the specified replicas are
  #  unavailable or unhealthy. The default value is `false`.
  directed_read_options_for_client = {
    include_replicas: {
      replica_selections: [{ location: "us-east4" }]
    }
  }

  # Instantiates a client with directedReadOptions
  spanner = Google::Cloud::Spanner.new project: project_id
  client  = spanner.client instance_id, database_id, directed_read_options: directed_read_options_for_client

  directed_read_options = {
    include_replicas: {
      replica_selections: [{ type: "READ_WRITE" }],
      auto_failover_disabled: true
    }
  }

  result = client.execute_sql "SELECT SingerId, AlbumId, AlbumTitle FROM Albums", directed_read_options: directed_read_options
  result.rows.each do |row|
    puts "SingerId: #{row[:SingerId]}"
    puts "AlbumId: #{row[:AlbumId]}"
    puts "AlbumTitle: #{row[:AlbumTitle]}"
  end
  puts "Successfully executed read-only transaction with directed_read_options"
end

REST

אפשר להשתמש בממשקי ה-API הבאים ל-REST כדי לבצע קריאות ממוקדות:

לדוגמה, כדי לבצע קריאות ממוקדות ב-us-central1 באמצעות executeSQL:

  1. לוחצים על projects.instances.databases.sessions.executeSql.

  2. בשדה session, מזינים:

    projects/<VAR>PROJECT-ID</VAR>/instances/<VAR>INSTANCE-ID</VAR>/databases/<VAR>DATABASE-ID</VAR>/sessions/<VAR>SESSION-ID</VAR>
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT-ID: מזהה הפרויקט.
    • INSTANCE-ID: מזהה המכונה.
    • DATABASE-ID: מזהה מסד הנתונים.
    • SESSION-ID: מזהה הסשן. הערך SESSION-ID מתקבל כשיוצרים סשן.
  3. בקטע גוף הבקשה, משתמשים בערכים הבאים:

    {
      "directedReadOptions": {
        "includeReplicas": {
          "replicaSelections": [
            {
              "location": "us-central1",
            }
          ]
        }
      },
      "sql": "SELECT SingerId, AlbumId, AlbumTitle FROM Albums"
    }
    
  4. לוחצים על Execute. התשובה תציג את תוצאות השאילתה.

RPC

אפשר להשתמש בממשקי ה-API הבאים של RPC כדי לבצע קריאות מכוונות:

מעקב

‫Spanner מספק מדד של זמן האחזור כדי לעזור לכם לעקוב אחרי פעילויות של קריאות ישירות במופעים. המדד זמין ב-Cloud Monitoring.

  • spanner.googleapis.com/api/read_request_latencies_by_serving_location

אפשר לסנן את המדד הזה באמצעות השדות /serving_location או /is_directed_read. השדה /serving location מציין את המיקום של שרת Spanner שממנו מוגשת הבקשה. השדה /is_directed_read מציין אם האפשרות של קריאות ממוקדות מופעלת.

רשימה מלאה של המדדים הזמינים מופיעה במאמר בנושא רשימת המדדים של Spanner.

המאמרים הבאים