

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Passaggio 2: verifica la connettività al registro
<a name="getting-started.java.step-2"></a>

**Importante**  
Avviso di fine del supporto: i clienti esistenti potranno utilizzare Amazon QLDB fino alla fine del supporto, il 31/07/2025. Per ulteriori dettagli, consulta [Migrare un registro Amazon QLDB su Amazon Aurora PostgreSQL](https://aws.amazon.com/blogs/database/migrate-an-amazon-qldb-ledger-to-amazon-aurora-postgresql/).

In questo passaggio, verifichi di poterti connettere al `vehicle-registration` registro in Amazon QLDB utilizzando l'endpoint API dei dati transazionali.

**Per testare la connettività al registro**

1. Esamina il seguente programma (`ConnectToLedger.java`), che crea una connessione della sessione di dati al `vehicle-registration` registro.

------
#### [ 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**  
Per eseguire operazioni sui dati sul registro, è necessario creare un'istanza della `QldbDriver` classe per connettersi a un registro specifico. Si tratta di un oggetto client diverso dal `AmazonQLDB` client utilizzato nel passaggio precedente per creare il registro. Quel client precedente viene utilizzato solo per eseguire le operazioni dell'API di gestione elencate in. [Riferimento all'API Amazon QLDB](api-reference.md)
Innanzitutto, crea un `QldbDriver` oggetto. È necessario specificare un nome contabile quando si crea questo driver.  
Quindi, è possibile utilizzare il `execute` metodo di questo driver per eseguire istruzioni PartiQL.
Facoltativamente, è possibile specificare un numero massimo di tentativi di nuovo tentativo per le eccezioni delle transazioni. Il `execute` metodo riprova automaticamente i conflitti OCC (Optimistic Concurrency Control) e altre eccezioni transitorie comuni entro questo limite configurabile. Il valore predefinito è `4`.  
Se la transazione continua a fallire dopo il raggiungimento del limite, il driver genera l'eccezione. Per ulteriori informazioni, consulta [Comprendere la politica dei nuovi tentativi con il driver in Amazon QLDB](driver-retry-policy.md).

------
#### [ 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**  
Per eseguire operazioni sui dati sul registro, è necessario creare un'istanza della `QldbDriver` classe `PooledQldbDriver` or per connettersi a un registro specifico. Si tratta di un oggetto client diverso dal `AmazonQLDB` client utilizzato nel passaggio precedente per creare il registro. Quel client precedente viene utilizzato solo per eseguire le operazioni dell'API di gestione elencate in. [Riferimento all'API Amazon QLDB](api-reference.md)  
Si consiglia di utilizzare, `PooledQldbDriver` a meno che non sia necessario implementare un pool di sessioni personalizzato con`QldbDriver`. La dimensione predefinita del pool `PooledQldbDriver` è il [numero massimo di connessioni HTTP aperte](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/ClientConfiguration.html#getMaxConnections--) consentite dal client di sessione.
Innanzitutto, crea un `PooledQldbDriver` oggetto. È necessario specificare un nome contabile quando si crea questo driver.  
Quindi, è possibile utilizzare il `execute` metodo di questo driver per eseguire istruzioni PartiQL. In alternativa, è possibile creare manualmente una sessione da questo oggetto driver in pool e utilizzare il metodo della `execute` sessione. Una sessione rappresenta una singola connessione con il registro.
Facoltativamente, è possibile specificare un numero massimo di tentativi per le eccezioni delle transazioni. Il `execute` metodo riprova automaticamente i conflitti OCC (Optimistic Concurrency Control) e altre eccezioni transitorie comuni entro questo limite configurabile. Il valore predefinito è `4`.  
Se la transazione continua a fallire dopo il raggiungimento del limite, il driver genera l'eccezione. Per ulteriori informazioni, consulta [Comprendere la politica dei nuovi tentativi con il driver in Amazon QLDB](driver-retry-policy.md).

------

1. Compila ed esegui il `ConnectToLedger.java` programma per testare la connettività della sessione di dati al `vehicle-registration` registro.

**Sovrascrivere il Regione AWS**

L'applicazione di esempio si connette a QLDB come Regione AWS impostazione predefinita, che puoi impostare come descritto nel passaggio dei prerequisiti. [Impostazione delle AWS credenziali e della regione predefinite](getting-started.java.md#getting-started.java.credentials) È inoltre possibile modificare la regione modificando le proprietà del generatore del client di sessione QLDB.

------
#### [ 2.x ]

Il seguente esempio di codice crea un'istanza di un nuovo oggetto. `QldbSessionClientBuilder`

```
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);
```

Puoi utilizzare il `region` metodo per eseguire il codice su QLDB in qualsiasi regione in cui è disponibile. Per un elenco completo, consulta gli [endpoint e le quote di Amazon QLDB](https://docs.aws.amazon.com/general/latest/gr/qldb.html) nel. *Riferimenti generali di AWS*

------
#### [ 1.x ]

Il seguente esempio di codice crea un'istanza di un nuovo oggetto. `AmazonQLDBSessionClientBuilder`

```
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);
```

Puoi utilizzare il `withRegion` metodo per eseguire il codice su QLDB in qualsiasi regione in cui è disponibile. Per un elenco completo, consulta gli [endpoint e le quote di Amazon QLDB](https://docs.aws.amazon.com/general/latest/gr/qldb.html) nel. *Riferimenti generali di AWS*

------

Per creare tabelle nel `vehicle-registration` registro, procedi a. [Passaggio 3: Creare tabelle, indici e dati di esempio](getting-started.java.step-3.md)