Paso 2: probar la conectividad con el libro mayor - Base de datos Amazon Quantum Ledger (AmazonQLDB)

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Paso 2: probar la conectividad con el libro mayor

importante

Aviso de fin de soporte: los clientes actuales podrán usar Amazon QLDB hasta que finalice el soporte, el 31 de julio de 2025. Para obtener más información, consulte Migración de un Amazon QLDB Ledger a Amazon Aurora SQL Postgre.

En este paso, verifica que puede conectarse al vehicle-registration libro mayor de Amazon QLDB mediante el punto de conexión de datos API transaccionales.

Para probar la conectividad con el libro mayor
  1. Utilice el siguiente programa (ConnectToLedger.java) para crear una conexión de sesión de datos con el libro mayor vehicle-registration.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import java.net.URI; import java.net.URISyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.services.qldbsession.QldbSessionClient; import software.amazon.awssdk.services.qldbsession.QldbSessionClientBuilder; import software.amazon.qldb.QldbDriver; import software.amazon.qldb.RetryPolicy; /** * Connect to a session for a given ledger using default settings. * <p> * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class ConnectToLedger { public static final Logger log = LoggerFactory.getLogger(ConnectToLedger.class); public static AwsCredentialsProvider credentialsProvider; public static String endpoint = null; public static String ledgerName = Constants.LEDGER_NAME; public static String region = null; public static QldbDriver driver; private ConnectToLedger() { } /** * Create a pooled driver for creating sessions. * * @param retryAttempts How many times the transaction will be retried in * case of a retryable issue happens like Optimistic Concurrency Control exception, * server side failures or network issues. * @return The pooled driver for creating sessions. */ public static QldbDriver createQldbDriver(int retryAttempts) { QldbSessionClientBuilder builder = getAmazonQldbSessionClientBuilder(); return QldbDriver.builder() .ledger(ledgerName) .transactionRetryPolicy(RetryPolicy .builder() .maxRetries(retryAttempts) .build()) .sessionClientBuilder(builder) .build(); } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static QldbDriver createQldbDriver() { QldbSessionClientBuilder builder = getAmazonQldbSessionClientBuilder(); return QldbDriver.builder() .ledger(ledgerName) .transactionRetryPolicy(RetryPolicy.builder() .maxRetries(Constants.RETRY_LIMIT).build()) .sessionClientBuilder(builder) .build(); } /** * Creates a QldbSession builder that is passed to the QldbDriver to connect to the Ledger. * * @return An instance of the AmazonQLDBSessionClientBuilder */ public static QldbSessionClientBuilder getAmazonQldbSessionClientBuilder() { QldbSessionClientBuilder builder = QldbSessionClient.builder(); if (null != endpoint && null != region) { try { builder.endpointOverride(new URI(endpoint)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } if (null != credentialsProvider) { builder.credentialsProvider(credentialsProvider); } return builder; } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static QldbDriver getDriver() { if (driver == null) { driver = createQldbDriver(); } return driver; } public static void main(final String... args) { Iterable<String> tables = ConnectToLedger.getDriver().getTableNames(); log.info("Existing tables in the ledger:"); for (String table : tables) { log.info("- {} ", table); } } }
    nota
    • Para ejecutar operaciones de datos en su libro mayor, debe crear una instancia de la clase QldbDriver para conectarse a un libro mayor específico. Se trata de un objeto de cliente diferente al cliente de AmazonQLDB que utilizó en el paso anterior para crear el libro mayor. Ese cliente anterior solo se utiliza para ejecutar las API operaciones de administración enumeradas en el. QLDBAPIReferencia de Amazon

    • En primer lugar, debe crear un objeto QldbDriver. Debe especificar un nombre de libro mayor al crear este controlador.

      A continuación, puede utilizar el método execute de este controlador para ejecutar instrucciones PartiQL.

    • Si lo desea, puede especificar un número máximo de reintentos para las excepciones de transacción. El execute método reintenta automáticamente los conflictos de control de simultaneidad optimista (OCC) y otras excepciones transitorias comunes hasta este límite configurable. El valor predeterminado es 4.

      Si la transacción sigue fallando una vez alcanzado el límite, el controlador lanza la excepción. Para obtener más información, consulte Descripción de la política de reintentos con el conductor en Amazon QLDB.

    1.x
    /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.qldbsession.AmazonQLDBSessionClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.PooledQldbDriver; import software.amazon.qldb.QldbDriver; import software.amazon.qldb.QldbSession; import software.amazon.qldb.exceptions.QldbClientException; /** * Connect to a session for a given ledger using default settings. * <p> * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class ConnectToLedger { public static final Logger log = LoggerFactory.getLogger(ConnectToLedger.class); public static AWSCredentialsProvider credentialsProvider; public static String endpoint = null; public static String ledgerName = Constants.LEDGER_NAME; public static String region = null; private static PooledQldbDriver driver; private ConnectToLedger() { } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static PooledQldbDriver createQldbDriver() { AmazonQLDBSessionClientBuilder builder = AmazonQLDBSessionClientBuilder.standard(); if (null != endpoint && null != region) { builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region)); } if (null != credentialsProvider) { builder.setCredentials(credentialsProvider); } return PooledQldbDriver.builder() .withLedger(ledgerName) .withRetryLimit(Constants.RETRY_LIMIT) .withSessionClientBuilder(builder) .build(); } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static PooledQldbDriver getDriver() { if (driver == null) { driver = createQldbDriver(); } return driver; } /** * Connect to a ledger through a {@link QldbDriver}. * * @return {@link QldbSession}. */ public static QldbSession createQldbSession() { return getDriver().getSession(); } public static void main(final String... args) { try (QldbSession qldbSession = createQldbSession()) { log.info("Listing table names "); for (String tableName : qldbSession.getTableNames()) { log.info(tableName); } } catch (QldbClientException e) { log.error("Unable to create session.", e); } } }
    nota
    • Para ejecutar operaciones de datos en su libro mayor, debe crear una instancia de la clase PooledQldbDriver o QldbDriver para conectarse a un libro mayor específico. Se trata de un objeto de cliente diferente al cliente de AmazonQLDB que utilizó en el paso anterior para crear el libro mayor. Ese cliente anterior solo se usa para ejecutar las API operaciones de administración enumeradas en. QLDBAPIReferencia de Amazon

      Recomendamos usar PooledQldbDriver a menos que necesite implementar un grupo de sesiones personalizado con QldbDriver. El tamaño predeterminado del grupo PooledQldbDriver es el número máximo de HTTP conexiones abiertas que permite el cliente de sesión.

    • En primer lugar, debe crear un objeto PooledQldbDriver. Debe especificar un nombre de libro mayor al crear este controlador.

      A continuación, puede utilizar el método execute de este controlador para ejecutar instrucciones PartiQL. O bien, puede crear manualmente una sesión a partir de este objeto controlador agrupado y utilizar el método execute de la sesión. Una sesión representa una conexión única con el libro mayor.

    • Si lo desea, puede especificar un número máximo de reintentos para las excepciones de transacción. El execute método reintenta automáticamente los conflictos de control de simultaneidad optimista (OCC) y otras excepciones transitorias comunes hasta este límite configurable. El valor predeterminado es 4.

      Si la transacción sigue fallando una vez alcanzado el límite, el controlador lanza la excepción. Para obtener más información, consulte Descripción de la política de reintentos con el conductor en Amazon QLDB.

  2. Compila y ejecuta el programa ConnectToLedger.java para probar la conectividad de la sesión de datos con el libro mayor vehicle-registration.

Anulando el Región de AWS

La aplicación de ejemplo se conecta QLDB de forma predeterminada Región de AWS, que puede configurar como se describe en el paso Configuración de la región y las credenciales de AWS predeterminadas previo. También puede cambiar la región modificando las propiedades del generador de clientes de QLDB sesión.

2.x

En el siguiente ejemplo de código se crea una instancia de objeto de QldbSessionClientBuilder nuevo.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.qldbsession.QldbSessionClientBuilder; // This client builder will default to US East (Ohio) QldbSessionClientBuilder builder = QldbSessionClient.builder() .region(Region.US_EAST_2);

Puede usar el region método para ejecutar el código QLDB en cualquier región en la que esté disponible. Para obtener una lista completa, consulta los QLDBpuntos de conexión y las cuotas de Amazon en. Referencia general de AWS

1.x

En el siguiente ejemplo de código se crea una instancia de objeto de AmazonQLDBSessionClientBuilder nuevo.

import com.amazonaws.regions.Regions; import com.amazonaws.services.qldbsession.AmazonQLDBSessionClientBuilder; // This client builder will default to US East (Ohio) AmazonQLDBSessionClientBuilder builder = AmazonQLDBSessionClientBuilder.standard() .withRegion(Regions.US_EAST_2);

Puedes usar el withRegion método para ejecutar tu código QLDB en cualquier región en la que esté disponible. Para obtener una lista completa, consulta los QLDBpuntos de conexión y las cuotas de Amazon en. Referencia general de AWS

Para crear tablas en el libro mayor vehicle-registration, continúe con Paso 3: cree tablas, índices y datos de muestra.