

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à.

# Utilizzalo StreamManagerClient per lavorare con gli stream
<a name="work-with-streams"></a>

I componenti Greengrass definiti dall'utente che vengono eseguiti sul dispositivo principale Greengrass possono utilizzare `StreamManagerClient` l'oggetto nell'SDK Stream Manager per creare flussi [in](manage-data-streams.md) stream manager e quindi interagire con i flussi. Quando un componente crea uno stream, definisce le Cloud AWS destinazioni, la prioritizzazione e altre politiche di esportazione e conservazione dei dati per lo stream. Per inviare dati allo stream manager, i componenti aggiungono i dati allo stream. Se viene definita una destinazione di esportazione per lo stream, lo stream manager esporta lo stream automaticamente.

**Nota**  
<a name="stream-manager-clients"></a>In genere, i client di stream manager sono componenti Greengrass definiti dall'utente. Se il tuo business case lo richiede, puoi anche consentire ai processi non componenti in esecuzione sul core di Greengrass (ad esempio, un contenitore Docker) di interagire con lo stream manager. Per ulteriori informazioni, consulta [Autenticazione client](manage-data-streams.md#stream-manager-security-client-authentication).

Gli snippet di questo argomento mostrano come i client chiamano i `StreamManagerClient` metodi per lavorare con gli stream. Per i dettagli di implementazione sui metodi e i relativi argomenti, utilizzate i collegamenti al riferimento SDK elencati dopo ogni frammento. 

Se usi stream manager in una funzione Lambda, la tua funzione Lambda dovrebbe creare un'istanza `StreamManagerClient` all'esterno del gestore della funzione. Se viene creata un'istanza nel gestore, la funzione crea un `client` e una connessione al gestore flussi ogni volta che viene richiamata.

**Nota**  
Se si esegue un'istanza `StreamManagerClient` nel gestore, è necessario chiamare esplicitamente il metodo `close()` quando `client` completa il suo lavoro. In caso contrario, `client` mantiene la connessione aperta e un altro thread in esecuzione fino alla chiusura dello script.

`StreamManagerClient` supporta le seguenti operazioni:
+ [Creazione del flusso di messaggi](#streammanagerclient-create-message-stream)
+ [Aggiunta di un messaggio](#streammanagerclient-append-message)
+ [Lettura di messaggi](#streammanagerclient-read-messages)
+ [Visualizzazione dell'elenco di flussi](#streammanagerclient-list-streams)
+ [Descrizione del flusso di messaggi](#streammanagerclient-describe-message-stream)
+ [Aggiorna il flusso di messaggi](#streammanagerclient-update-message-stream)
+ [Eliminazione del flusso di messaggi](#streammanagerclient-delete-message-stream)

## Creazione del flusso di messaggi
<a name="streammanagerclient-create-message-stream"></a>

Per creare uno stream, un componente Greengrass definito dall'utente chiama il metodo create e passa un oggetto. `MessageStreamDefinition` Questo oggetto specifica il nome univoco dello stream e definisce come lo stream manager deve gestire i nuovi dati quando viene raggiunta la dimensione massima del flusso. È possibile utilizzare `MessageStreamDefinition` e relativi tipi di dati (ad esempio `ExportDefinition`, `StrategyOnFull` e `Persistence`) per definire altre proprietà del flusso. Ciò include:
+ L'obiettivo AWS IoT Analytics, Kinesis Data AWS IoT SiteWise Streams e le destinazioni Amazon S3 per le esportazioni automatiche. Per ulteriori informazioni, consulta [Esporta le configurazioni per le destinazioni supportate Cloud AWS](stream-export-configurations.md).
+ Priorità di esportazione. Stream manager esporta i flussi con priorità più alta prima dei flussi con priorità più bassa.
+ Dimensione massima del batch e intervallo di batch per AWS IoT Analytics Kinesis Data Streams e destinazioni. AWS IoT SiteWise Stream manager esporta i messaggi quando viene soddisfatta una delle due condizioni.
+ Time-to-live (TTL). Il tempo necessario per garantire che i dati del flusso siano disponibili per l'elaborazione. È necessario assicurarsi che i dati possano essere utilizzati entro questo periodo di tempo. Questa non è una policy di eliminazione. È possibile che i dati non vengano eliminati immediatamente dopo il periodo TTL.
+ Persistenza del flusso. Scegliere di salvare i flussi nel file system per mantenere i dati tra riavvii core o salvare i flussi in memoria.
+ Numero di sequenza iniziale. Specificate il numero di sequenza del messaggio da utilizzare come messaggio iniziale nell'esportazione.

Per ulteriori informazioni su`MessageStreamDefinition`, consultate il riferimento SDK per la lingua di destinazione:
+ [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/MessageStreamDefinition.html)nell'SDK Java
+ [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.MessageStreamDefinition.html)nell'SDK Node.js
+ [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.MessageStreamDefinition)nell'SDK Python

**Nota**  
<a name="streammanagerclient-http-config"></a>`StreamManagerClient`fornisce anche una destinazione di destinazione che è possibile utilizzare per esportare flussi su un server HTTP. Questo target è destinato esclusivamente a scopi di test. Non è stabile né è supportato per l'uso in ambienti di produzione.

Dopo aver creato uno stream, i componenti Greengrass possono [aggiungere messaggi](#streammanagerclient-append-message) allo stream per inviare dati per l'esportazione e [leggere i messaggi](#streammanagerclient-read-messages) dallo stream per l'elaborazione locale. Il numero di flussi creati dipende dalle funzionalità hardware e dal business case. Una strategia consiste nel creare un flusso per ogni canale di destinazione nel AWS IoT Analytics nostro flusso di dati Kinesis, sebbene sia possibile definire più destinazioni per un flusso. Un flusso ha una lunga durata.

### Requisiti
<a name="streammanagerclient-create-message-stream-reqs"></a>

Questa operazione ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-create-message-stream-examples"></a>

Il frammento di codice seguente crea un flusso denominato `StreamName`. Definisce le proprietà dello `MessageStreamDefinition` stream nei tipi di dati subordinati.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    client.create_message_stream(MessageStreamDefinition(
        name="StreamName",    # Required.
        max_size=268435456,    # Default is 256 MB.
        stream_segment_size=16777216,    # Default is 16 MB.
        time_to_live_millis=None,    # By default, no TTL is enabled.
        strategy_on_full=StrategyOnFull.OverwriteOldestData,    # Required.
        persistence=Persistence.File,    # Default is File.
        flush_on_write=False,    # Default is false.
        export_definition=ExportDefinition(    # Optional. Choose where/how the stream is exported to the Cloud AWS.
            kinesis=None,
            iot_analytics=None,
            iot_sitewise=None,
            s3_task_executor=None
        )
    ))
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: create\$1message\$1stream \$1 [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.MessageStreamDefinition)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.create_message_stream)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    client.createMessageStream(
            new MessageStreamDefinition()
                    .withName("StreamName") // Required.
                    .withMaxSize(268435456L)    // Default is 256 MB.
                    .withStreamSegmentSize(16777216L)    // Default is 16 MB.
                    .withTimeToLiveMillis(null)    // By default, no TTL is enabled.
                    .withStrategyOnFull(StrategyOnFull.OverwriteOldestData)    // Required.
                    .withPersistence(Persistence.File)    // Default is File.
                    .withFlushOnWrite(false)    // Default is false.
                    .withExportDefinition(    // Optional. Choose where/how the stream is exported to the Cloud AWS.
                            new ExportDefinition()
                                    .withKinesis(null)
                                    .withIotAnalytics(null)
                                    .withIotSitewise(null)
                                    .withS3(null)
                    )
 
    );
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

Riferimento a Java [createMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#createMessageStream-com.amazonaws.greengrass.streammanager.model.MessageStreamDefinition-)SDK: \$1 [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/MessageStreamDefinition.html)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
  try {
    await client.createMessageStream(
      new MessageStreamDefinition()
        .withName("StreamName") // Required.
        .withMaxSize(268435456)  // Default is 256 MB.
        .withStreamSegmentSize(16777216)  // Default is 16 MB.
        .withTimeToLiveMillis(null)  // By default, no TTL is enabled.
        .withStrategyOnFull(StrategyOnFull.OverwriteOldestData)  // Required.
        .withPersistence(Persistence.File)  // Default is File.
        .withFlushOnWrite(false)  // Default is false.
        .withExportDefinition(  // Optional. Choose where/how the stream is exported to the Cloud AWS.
          new ExportDefinition()
            .withKinesis(null)
            .withIotAnalytics(null)
            .withIotSiteWise(null)
            .withS3(null)
        )
    );
  } catch (e) {
    // Properly handle errors.
  }
});
client.onError((err) => {
  // Properly handle connection errors.
  // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: \$1 [createMessageStream[MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.MessageStreamDefinition.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#createMessageStream)

------

Per ulteriori informazioni sulla configurazione delle destinazioni di esportazione, consulta. [Esporta le configurazioni per le destinazioni supportate Cloud AWS](stream-export-configurations.md)

## Aggiunta di un messaggio
<a name="streammanagerclient-append-message"></a>

Per inviare dati allo stream manager per l'esportazione, i componenti Greengrass aggiungono i dati allo stream di destinazione. La destinazione di esportazione determina il tipo di dati da passare a questo metodo.

### Requisiti
<a name="streammanagerclient-append-message-reqs"></a>

Questa operazione presenta i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-append-message-examples"></a>

#### AWS IoT Analytics o destinazioni di esportazione Kinesis Data Streams
<a name="streammanagerclient-append-message-blob"></a>

Il frammento di codice seguente aggiunge un messaggio al flusso denominato `StreamName`. Per le AWS IoT Analytics nostre destinazioni Kinesis Data Streams, i componenti Greengrass aggiungono un blob di dati.

Questo frammento ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    sequence_number = client.append_message(stream_name="StreamName", data=b'Arbitrary bytes data')
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: append\$1message](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.append_message)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    long sequenceNumber = client.appendMessage("StreamName", "Arbitrary byte array".getBytes());
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

[Riferimento Java SDK: AppendMessage](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#appendMessage-java.lang.String-byte:A-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const sequenceNumber = await client.appendMessage("StreamName", Buffer.from("Arbitrary byte array"));
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

[Riferimento all'SDK Node.js: appendMessage](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#appendMessage)

------

#### AWS IoT SiteWise destinazioni di esportazione
<a name="streammanagerclient-append-message-sitewise"></a>

Il frammento di codice seguente aggiunge un messaggio al flusso denominato `StreamName`. Per le AWS IoT SiteWise destinazioni, i componenti Greengrass aggiungono un oggetto serializzato. `PutAssetPropertyValueEntry` Per ulteriori informazioni, consulta [Esportazione in AWS IoT SiteWise](stream-export-configurations.md#export-streams-to-sitewise).

**Nota**  
<a name="BatchPutAssetPropertyValue-data-reqs"></a>Quando si inviano dati a AWS IoT SiteWise, i dati devono soddisfare i requisiti dell'azione. `BatchPutAssetPropertyValue` Per ulteriori informazioni, consulta [BatchPutAssetPropertyValue](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_BatchPutAssetPropertyValue.html) nella *documentazione di riferimento dell’API AWS IoT SiteWise *.

Questo frammento presenta i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    # SiteWise requires unique timestamps in all messages and also needs timestamps not earlier
    # than 10 minutes in the past. Add some randomness to time and offset.

    # Note: To create a new asset property data, you should use the classes defined in the
    # greengrasssdk.stream_manager module.

    time_in_nanos = TimeInNanos(
        time_in_seconds=calendar.timegm(time.gmtime()) - random.randint(0, 60), offset_in_nanos=random.randint(0, 10000)
    )
    variant = Variant(double_value=random.random())
    asset = [AssetPropertyValue(value=variant, quality=Quality.GOOD, timestamp=time_in_nanos)]
    putAssetPropertyValueEntry = PutAssetPropertyValueEntry(entry_id=str(uuid.uuid4()), property_alias="PropertyAlias", property_values=asset)
    sequence_number = client.append_message(stream_name="StreamName", Util.validate_and_serialize_to_json_bytes(putAssetPropertyValueEntry))
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: append\$1message \$1 [PutAssetPropertyValueEntry](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.PutAssetPropertyValueEntry)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.append_message)

------
#### [ Java ]

```
try (final StreamManagerClient client = GreengrassClientBuilder.streamManagerClient().build()) {
    Random rand = new Random();
    // Note: To create a new asset property data, you should use the classes defined in the
    // com.amazonaws.greengrass.streammanager.model.sitewise package.
    List<AssetPropertyValue> entries = new ArrayList<>() ;

    // IoTSiteWise requires unique timestamps in all messages and also needs timestamps not earlier
    // than 10 minutes in the past. Add some randomness to time and offset.
    final int maxTimeRandomness = 60;
    final int maxOffsetRandomness = 10000;
    double randomValue = rand.nextDouble();
    TimeInNanos timestamp = new TimeInNanos()
            .withTimeInSeconds(Instant.now().getEpochSecond() - rand.nextInt(maxTimeRandomness))
            .withOffsetInNanos((long) (rand.nextInt(maxOffsetRandomness)));
    AssetPropertyValue entry = new AssetPropertyValue()
            .withValue(new Variant().withDoubleValue(randomValue))
            .withQuality(Quality.GOOD)
            .withTimestamp(timestamp);
    entries.add(entry);

    PutAssetPropertyValueEntry putAssetPropertyValueEntry = new PutAssetPropertyValueEntry()
            .withEntryId(UUID.randomUUID().toString())
            .withPropertyAlias("PropertyAlias")
            .withPropertyValues(entries);
    long sequenceNumber = client.appendMessage("StreamName", ValidateAndSerialize.validateAndSerializeToJsonBytes(putAssetPropertyValueEntry));
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

Riferimento Java SDK: [appendMessage \$1 [PutAssetPropertyValueEntry](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/sitewise/PutAssetPropertyValueEntry.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#appendMessage-java.lang.String-byte:A-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const maxTimeRandomness = 60;
        const maxOffsetRandomness = 10000;
        const randomValue = Math.random();
        // Note: To create a new asset property data, you should use the classes defined in the
        // aws-greengrass-core-sdk StreamManager module.
        const timestamp = new TimeInNanos()
            .withTimeInSeconds(Math.round(Date.now() / 1000) - Math.floor(Math.random() - maxTimeRandomness))
            .withOffsetInNanos(Math.floor(Math.random() * maxOffsetRandomness));
        const entry = new AssetPropertyValue()
            .withValue(new Variant().withDoubleValue(randomValue))
            .withQuality(Quality.GOOD)
            .withTimestamp(timestamp);

        const putAssetPropertyValueEntry =    new PutAssetPropertyValueEntry()
            .withEntryId(`${ENTRY_ID_PREFIX}${i}`)
            .withPropertyAlias("PropertyAlias")
            .withPropertyValues([entry]);
        const sequenceNumber = await client.appendMessage("StreamName", util.validateAndSerializeToJsonBytes(putAssetPropertyValueEntry));
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: [appendMessage \$1 [PutAssetPropertyValueEntry](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.PutAssetPropertyValueEntry.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#appendMessage)

------

#### Destinazioni di esportazione Amazon S3
<a name="streammanagerclient-append-message-export-task"></a>

Il seguente frammento aggiunge un'attività di esportazione allo stream denominato. `StreamName` Per le destinazioni Amazon S3, i componenti Greengrass aggiungono un oggetto serializzato che contiene informazioni sul file di input di origine e sull'`S3ExportTaskDefinition`oggetto Amazon S3 di destinazione. Se l'oggetto specificato non esiste, Stream Manager lo crea per te. Per ulteriori informazioni, consulta [Esportazione su Amazon S3](stream-export-configurations.md#export-streams-to-s3).

Questo frammento ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    # Append an Amazon S3 Task definition and print the sequence number.
    s3_export_task_definition = S3ExportTaskDefinition(input_url="URLToFile", bucket="BucketName", key="KeyName")
    sequence_number = client.append_message(stream_name="StreamName", Util.validate_and_serialize_to_json_bytes(s3_export_task_definition))
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.append_message](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.append_message)

------
#### [ Java ]

```
try (final StreamManagerClient client = GreengrassClientBuilder.streamManagerClient().build()) {
    // Append an Amazon S3 export task definition and print the sequence number.
    S3ExportTaskDefinition s3ExportTaskDefinition = new S3ExportTaskDefinition()
        .withBucket("BucketName")
        .withKey("KeyName")
        .withInputUrl("URLToFile");
    long sequenceNumber = client.appendMessage("StreamName", ValidateAndSerialize.validateAndSerializeToJsonBytes(s3ExportTaskDefinition));
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

[Riferimento a Java SDK: [appendMessage \$1](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#appendMessage-java.lang.String-byte:A-) S3 ExportTaskDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/S3ExportTaskDefinition.html)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
     // Append an Amazon S3 export task definition and print the sequence number.
     const taskDefinition = new S3ExportTaskDefinition()
        .withBucket("BucketName")
        .withKey("KeyName")
        .withInputUrl("URLToFile");
        const sequenceNumber = await client.appendMessage("StreamName", util.validateAndSerializeToJsonBytes(taskDefinition)));
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

[Riferimento all'SDK Node.js: [appendMessage \$1](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#appendMessage) S3 ExportTaskDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.S3ExportTaskDefinition.html)

------

## Lettura di messaggi
<a name="streammanagerclient-read-messages"></a>

Leggi i messaggi da uno stream.

### Requisiti
<a name="streammanagerclient-read-messages-reqs"></a>

Questa operazione ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-read-messages-examples"></a>

Il frammento di codice seguente legge i messaggi dal flusso denominato `StreamName`. Il metodo di lettura accetta un oggetto `ReadMessagesOptions` facoltativo che specifica il numero di sequenza da cui iniziare la lettura, i numeri minimo e massimo da leggere e un timeout per la lettura dei messaggi.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    message_list = client.read_messages(
        stream_name="StreamName",
        # By default, if no options are specified, it tries to read one message from the beginning of the stream.
        options=ReadMessagesOptions(
            desired_start_sequence_number=100,
            # Try to read from sequence number 100 or greater. By default, this is 0.
            min_message_count=10,
            # Try to read 10 messages. If 10 messages are not available, then NotEnoughMessagesException is raised. By default, this is 1.
            max_message_count=100,    # Accept up to 100 messages. By default this is 1.
            read_timeout_millis=5000
            # Try to wait at most 5 seconds for the min_messsage_count to be fulfilled. By default, this is 0, which immediately returns the messages or an exception.
        )
    )
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: read\$1messages \$1 [ReadMessagesOptions](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.ReadMessagesOptions)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.read_messages)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    List<Message> messages = client.readMessages("StreamName",
            // By default, if no options are specified, it tries to read one message from the beginning of the stream.
            new ReadMessagesOptions()
                    // Try to read from sequence number 100 or greater. By default this is 0.
                    .withDesiredStartSequenceNumber(100L)
                    // Try to read 10 messages. If 10 messages are not available, then NotEnoughMessagesException is raised. By default, this is 1.
                    .withMinMessageCount(10L)
                    // Accept up to 100 messages. By default this is 1.
                    .withMaxMessageCount(100L)
                    // Try to wait at most 5 seconds for the min_messsage_count to be fulfilled. By default, this is 0, which immediately returns the messages or an exception.
                    .withReadTimeoutMillis(Duration.ofSeconds(5L).toMillis())
    );
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

Riferimento a Java SDK: [ReadMessages \$1 [ReadMessagesOptions](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/ReadMessagesOptions.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#readMessages-java.lang.String-com.amazonaws.greengrass.streammanager.model.ReadMessagesOptions-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const messages = await client.readMessages("StreamName",
            // By default, if no options are specified, it tries to read one message from the beginning of the stream.
            new ReadMessagesOptions()
                // Try to read from sequence number 100 or greater. By default this is 0.
                .withDesiredStartSequenceNumber(100)
                // Try to read 10 messages. If 10 messages are not available, then NotEnoughMessagesException is thrown. By default, this is 1.
                .withMinMessageCount(10)
                // Accept up to 100 messages. By default this is 1.
                .withMaxMessageCount(100)
                // Try to wait at most 5 seconds for the minMessageCount to be fulfilled. By default, this is 0, which immediately returns the messages or an exception.
                .withReadTimeoutMillis(5 * 1000)
        );
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: [ReadMessages \$1 [ReadMessagesOptions](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.ReadMessagesOptions.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#readMessages)

------

## Visualizzazione dell'elenco di flussi
<a name="streammanagerclient-list-streams"></a>

Ottieni l'elenco degli stream nello stream manager.

### Requisiti
<a name="streammanagerclient-list-streams-reqs"></a>

Questa operazione ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-list-streams-examples"></a>

Il frammento di codice seguente ottiene un elenco dei flussi (per nome) in stream manager.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    stream_names = client.list_streams()
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: list\$1streams](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.list_streams)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    List<String> streamNames = client.listStreams();
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

[Riferimento a Java SDK: ListStreams](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#listStreams--)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const streams = await client.listStreams();
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

[Riferimento all'SDK Node.js: ListStreams](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#listStreams)

------

## Descrizione del flusso di messaggi
<a name="streammanagerclient-describe-message-stream"></a>

Ottieni i metadati relativi a uno stream, tra cui la definizione, la dimensione e lo stato dell'esportazione.

### Requisiti
<a name="streammanagerclient-describe-message-stream-reqs"></a>

Questa operazione ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-describe-message-stream-examples"></a>

Il frammento di codice seguente ottiene i metadati relativi al flusso denominato `StreamName`, inclusi la definizione, le dimensioni e gli stati di esportatore del flusso.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    stream_description = client.describe_message_stream(stream_name="StreamName")
    if stream_description.export_statuses[0].error_message:
        # The last export of export destination 0 failed with some error
        # Here is the last sequence number that was successfully exported
        stream_description.export_statuses[0].last_exported_sequence_number
 
    if (stream_description.storage_status.newest_sequence_number >
            stream_description.export_statuses[0].last_exported_sequence_number):
        pass
        # The end of the stream is ahead of the last exported sequence number
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: describe\$1message\$1stream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.describe_message_stream)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    MessageStreamInfo description = client.describeMessageStream("StreamName");
    String lastErrorMessage = description.getExportStatuses().get(0).getErrorMessage();
    if (lastErrorMessage != null && !lastErrorMessage.equals("")) {
        // The last export of export destination 0 failed with some error.
        // Here is the last sequence number that was successfully exported.
        description.getExportStatuses().get(0).getLastExportedSequenceNumber();
    }
 
    if (description.getStorageStatus().getNewestSequenceNumber() >
            description.getExportStatuses().get(0).getLastExportedSequenceNumber()) {
        // The end of the stream is ahead of the last exported sequence number.
    }
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

Riferimento a Java SDK: [describeMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#describeMessageStream-java.lang.String-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const description = await client.describeMessageStream("StreamName");
        const lastErrorMessage = description.exportStatuses[0].errorMessage;
        if (lastErrorMessage) {
            // The last export of export destination 0 failed with some error.
            // Here is the last sequence number that was successfully exported.
            description.exportStatuses[0].lastExportedSequenceNumber;
        }
 
        if (description.storageStatus.newestSequenceNumber >
            description.exportStatuses[0].lastExportedSequenceNumber) {
            // The end of the stream is ahead of the last exported sequence number.
        }
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: [describeMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#describeMessageStream)

------

## Aggiorna il flusso di messaggi
<a name="streammanagerclient-update-message-stream"></a>

Aggiorna le proprietà di uno stream esistente. Potresti voler aggiornare uno stream se i tuoi requisiti cambiano dopo la creazione dello stream. Esempio:
+ Aggiungi una nuova [configurazione di esportazione](stream-export-configurations.md) per una Cloud AWS destinazione.
+ Aumenta la dimensione massima di uno stream per modificare il modo in cui i dati vengono esportati o conservati. Ad esempio, la dimensione dello stream in combinazione con la tua strategia sulle impostazioni complete potrebbe comportare l'eliminazione o il rifiuto dei dati prima che lo stream manager possa elaborarli.
+ Metti in pausa e riprendi le esportazioni, ad esempio se le attività di esportazione richiedono molto tempo e desideri razionare i dati di caricamento.

I componenti Greengrass seguono questo processo di alto livello per aggiornare uno stream:

1. [Ottieni la descrizione dello stream.](#streammanagerclient-describe-message-stream)

1. Aggiorna le proprietà di destinazione sugli oggetti corrispondenti `MessageStreamDefinition` e subordinati.

1. Passa l'aggiornamento`MessageStreamDefinition`. Assicurati di includere le definizioni complete degli oggetti per lo stream aggiornato. Le proprietà non definite tornano ai valori predefiniti.

   È possibile specificare il numero di sequenza del messaggio da utilizzare come messaggio iniziale nell'esportazione.

### Requisiti
<a name="streammanagerclient-update-message-streamreqs"></a>

Questa operazione presenta i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-update-message-stream-examples"></a>

Il seguente frammento aggiorna lo stream denominato. `StreamName` Aggiorna più proprietà di un flusso che esporta in Kinesis Data Streams.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    message_stream_info = client.describe_message_stream(STREAM_NAME)
    message_stream_info.definition.max_size=536870912
    message_stream_info.definition.stream_segment_size=33554432
    message_stream_info.definition.time_to_live_millis=3600000
    message_stream_info.definition.strategy_on_full=StrategyOnFull.RejectNewData
    message_stream_info.definition.persistence=Persistence.Memory
    message_stream_info.definition.flush_on_write=False
    message_stream_info.definition.export_definition.kinesis=
        [KinesisConfig(    
            # Updating Export definition to add a Kinesis Stream configuration.
            identifier=str(uuid.uuid4()), kinesis_stream_name=str(uuid.uuid4()))]
    client.update_message_stream(message_stream_info.definition)
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

Riferimento a Python SDK: \$1 [updateMessageStream[MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.MessageStreamDefinition)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.update_message_stream)

------
#### [ Java ]

```
try (final StreamManagerClient client = GreengrassClientBuilder.streamManagerClient().build()) {
    MessageStreamInfo messageStreamInfo = client.describeMessageStream(STREAM_NAME);
    // Update the message stream with new values.
    client.updateMessageStream(
        messageStreamInfo.getDefinition()
            .withStrategyOnFull(StrategyOnFull.RejectNewData) // Required. Updating Strategy on full to reject new data.
            // Max Size update should be greater than initial Max Size defined in Create Message Stream request
            .withMaxSize(536870912L) // Update Max Size to 512 MB.
            .withStreamSegmentSize(33554432L) // Update Segment Size to 32 MB.
            .withFlushOnWrite(true) // Update flush on write to true.
            .withPersistence(Persistence.Memory) // Update the persistence to Memory.
            .withTimeToLiveMillis(3600000L)    // Update TTL to 1 hour.
            .withExportDefinition(
                // Optional. Choose where/how the stream is exported to the Cloud AWS.
                messageStreamInfo.getDefinition().getExportDefinition().
                    // Updating Export definition to add a Kinesis Stream configuration.
                    .withKinesis(new ArrayList<KinesisConfig>() {{
                        add(new KinesisConfig()
                            .withIdentifier(EXPORT_IDENTIFIER)
                            .withKinesisStreamName("test"));
                        }})
            );
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

[Riferimento a Java SDK: update\$1message\$1stream \$1 [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/MessageStreamDefinition.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#updateMessageStream-java.lang.String-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        const messageStreamInfo = await c.describeMessageStream(STREAM_NAME);
        await client.updateMessageStream(
            messageStreamInfo.definition
                // Max Size update should be greater than initial Max Size defined in Create Message Stream request
                .withMaxSize(536870912)    // Default is 256 MB. Updating Max Size to 512 MB.
                .withStreamSegmentSize(33554432)    // Default is 16 MB. Updating Segment Size to 32 MB.
                .withTimeToLiveMillis(3600000)    // By default, no TTL is enabled. Update TTL to 1 hour.
                .withStrategyOnFull(StrategyOnFull.RejectNewData)    // Required. Updating Strategy on full to reject new data.
                .withPersistence(Persistence.Memory)    // Default is File. Update the persistence to Memory
                .withFlushOnWrite(true)    // Default is false. Updating to true.
                .withExportDefinition(    
                    // Optional. Choose where/how the stream is exported to the Cloud AWS.
                    messageStreamInfo.definition.exportDefinition
                        // Updating Export definition to add a Kinesis Stream configuration.
                        .withKinesis([new KinesisConfig().withIdentifier(uuidv4()).withKinesisStreamName(uuidv4())])
                )
        );
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'[updateMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#updateMessageStream)SDK Node.js: \$1 [MessageStreamDefinition](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.MessageStreamDefinition.html)

------

### Vincoli per l'aggiornamento degli stream
<a name="streammanagerclient-update-constraints"></a>

I seguenti vincoli si applicano all'aggiornamento dei flussi. A meno che non sia indicato nell'elenco seguente, gli aggiornamenti hanno effetto immediato.
+ Non puoi aggiornare la persistenza di uno stream. Per modificare questo comportamento, [elimina lo stream](#streammanagerclient-delete-message-stream) e [crea uno stream](#streammanagerclient-create-message-stream) che definisca la nuova politica di persistenza.
+ Puoi aggiornare la dimensione massima di uno stream solo nelle seguenti condizioni:
  + La dimensione massima deve essere maggiore o uguale alla dimensione corrente dello stream. <a name="messagestreaminfo-describe-stream"></a>Per trovare queste informazioni, [descrivi lo stream](#streammanagerclient-describe-message-stream) e poi controlla lo stato di archiviazione dell'`MessageStreamInfo`oggetto restituito. 
  + La dimensione massima deve essere maggiore o uguale alla dimensione del segmento dello stream.
+ Puoi aggiornare la dimensione del segmento di stream a un valore inferiore alla dimensione massima dello stream. L'impostazione aggiornata si applica ai nuovi segmenti.
+ Gli aggiornamenti alla proprietà time to live (TTL) si applicano alle nuove operazioni di aggiunta. Se riduci questo valore, stream manager potrebbe anche eliminare i segmenti esistenti che superano il TTL.
+ Gli aggiornamenti alla strategia sulla proprietà completa si applicano alle nuove operazioni di aggiunta. Se imposti la strategia per sovrascrivere i dati più vecchi, stream manager potrebbe anche sovrascrivere i segmenti esistenti in base alla nuova impostazione.
+ Gli aggiornamenti alla proprietà flush on write si applicano ai nuovi messaggi.
+ Gli aggiornamenti alle configurazioni di esportazione si applicano alle nuove esportazioni. La richiesta di aggiornamento deve includere tutte le configurazioni di esportazione che si desidera supportare. Altrimenti, stream manager le elimina.
  + Quando aggiorni una configurazione di esportazione, specifica l'identificatore della configurazione di esportazione di destinazione.
  + Per aggiungere una configurazione di esportazione, specificate un identificatore univoco per la nuova configurazione di esportazione.
  + Per eliminare una configurazione di esportazione, omettete la configurazione di esportazione.
+ Per [aggiornare](#streammanagerclient-update-message-stream) il numero di sequenza iniziale di una configurazione di esportazione in uno stream, è necessario specificare un valore inferiore al numero di sequenza più recente. <a name="messagestreaminfo-describe-stream"></a>Per trovare queste informazioni, [descrivi lo stream](#streammanagerclient-describe-message-stream) e quindi controlla lo stato di archiviazione dell'`MessageStreamInfo`oggetto restituito. 

## Eliminazione del flusso di messaggi
<a name="streammanagerclient-delete-message-stream"></a>

Elimina un flusso. Quando si elimina un flusso, tutti i dati memorizzati per il flusso vengono eliminati dal disco.

### Requisiti
<a name="streammanagerclient-delete-message-stream-reqs"></a>

Questa operazione ha i seguenti requisiti:
+ <a name="streammanagerclient-min-sm-sdk"></a>Versione minima dell'SDK di Stream Manager: Python: 1.1.0 \$1 Java: 1.1.0 \$1 Node.js: 1.1.0

### Esempi
<a name="streammanagerclient-delete-message-stream-examples"></a>

Il frammento di codice seguente elimina il flusso denominato `StreamName`.

------
#### [ Python ]

```
client = StreamManagerClient()
 
try:
    client.delete_message_stream(stream_name="StreamName")
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

Riferimento all'SDK Python: [deleteMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.delete_message_stream)

------
#### [ Java ]

```
try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    client.deleteMessageStream("StreamName");
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

[Riferimento Java SDK: delete\$1message\$1stream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#deleteMessageStream-java.lang.String-)

------
#### [ Node.js ]

```
const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        await client.deleteMessageStream("StreamName");
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: [deleteMessageStream](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#deleteMessageStream)

------

## Consulta anche
<a name="work-with-streams-see-also"></a>
+ [Gestisci i flussi di dati sui dispositivi core Greengrass](manage-data-streams.md)
+ [Configurare AWS IoT Greengrass lo stream manager](configure-stream-manager.md)
+ [Esporta le configurazioni per le destinazioni supportate Cloud AWS](stream-export-configurations.md)
+ `StreamManagerClient`nel riferimento all'SDK di Stream Manager:
  + [Python](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html)
  + [Java](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html)
  + [Node.js](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html)

# Esporta le configurazioni per le destinazioni supportate Cloud AWS
<a name="stream-export-configurations"></a>

I componenti Greengrass definiti dall'utente vengono `StreamManagerClient` utilizzati nell'SDK Stream Manager per interagire con lo stream manager. Quando un componente [crea uno stream](work-with-streams.md#streammanagerclient-create-message-stream) o [aggiorna uno stream, passa un](work-with-streams.md#streammanagerclient-create-message-stream) `MessageStreamDefinition` oggetto che rappresenta le proprietà dello stream, inclusa la definizione di esportazione. L'`ExportDefinition`oggetto contiene le configurazioni di esportazione definite per lo stream. Stream Manager utilizza queste configurazioni di esportazione per determinare dove e come esportare lo stream.

![\[Diagramma del modello a oggetti del tipo di ExportDefinition proprietà.\]](http://docs.aws.amazon.com/it_it/greengrass/v2/developerguide/images/stream-manager-exportconfigs.png)


È possibile definire zero o più configurazioni di esportazione su uno stream, incluse più configurazioni di esportazione per un singolo tipo di destinazione. Ad esempio, puoi esportare uno stream su due AWS IoT Analytics canali e un flusso di dati Kinesis.

In caso di tentativi di esportazione falliti, stream manager riprova continuamente a esportare i dati verso il a Cloud AWS intervalli fino a cinque minuti. Il numero di tentativi di nuovo tentativo non ha un limite massimo.

**Nota**  
<a name="streammanagerclient-http-config"></a>`StreamManagerClient`fornisce anche una destinazione di destinazione che è possibile utilizzare per esportare i flussi su un server HTTP. Questo target è destinato esclusivamente a scopi di test. Non è stabile né è supportato per l'uso in ambienti di produzione.

**Topics**
+ [AWS IoT Analytics canali](#export-to-iot-analytics)
+ [Flussi di dati Amazon Kinesis](#export-to-kinesis)
+ [AWS IoT SiteWise proprietà degli asset](#export-to-iot-sitewise)
+ [Oggetti Amazon S3](#export-to-s3)

L'utente è responsabile del mantenimento di queste Cloud AWS risorse.

## AWS IoT Analytics canali
<a name="export-to-iot-analytics"></a>

Stream manager supporta le esportazioni automatiche verso AWS IoT Analytics. <a name="ita-export-destination"></a>AWS IoT Analytics consente di eseguire analisi avanzate sui dati per aiutare a prendere decisioni aziendali e migliorare i modelli di apprendimento automatico. Per ulteriori informazioni, consulta [Cos'è AWS IoT Analytics?](https://docs.aws.amazon.com/iotanalytics/latest/userguide/welcome.html) nella *Guida AWS IoT Analytics per l'utente*. 

Nell'SDK Stream Manager, i componenti Greengrass utilizzano per definire `IoTAnalyticsConfig` la configurazione di esportazione per questo tipo di destinazione. Per ulteriori informazioni, consultate il riferimento SDK per la lingua di destinazione:
+ [Io TAnalytics Config nell'SDK](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.IoTAnalyticsConfig) Python
+ [Io TAnalytics Config nell'SDK](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/export/IoTAnalyticsConfig.html) Java
+ [Io TAnalytics Config nell'SDK](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.IoTAnalyticsConfig.html) Node.js

### Requisiti
<a name="export-to-iot-analytics-reqs"></a>

Questa destinazione di esportazione presenta i seguenti requisiti:
+ I canali di destinazione in ingresso AWS IoT Analytics devono trovarsi nello stesso Account AWS dispositivo principale Greengrass. Regione AWS 
+ [Autorizza i dispositivi principali a interagire con i servizi AWS](device-service-role.md)Devono consentire l'`iotanalytics:BatchPutMessage`autorizzazione per i canali di destinazione. Esempio:

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "iotanalytics:BatchPutMessage"
        ],
        "Resource": [
          "arn:aws:iotanalytics:us-east-1:123456789012:channel/channel_1_name",
          "arn:aws:iotanalytics:us-east-1:123456789012:channel/channel_2_name"
        ]
      }
    ]
  }
  ```

------

  <a name="wildcards-grant-granular-conditional-access"></a>È possibile concedere un accesso granulare o condizionale alle risorse, ad esempio utilizzando uno schema di denominazione con caratteri jolly`*`. *Per ulteriori informazioni, consulta [Aggiungere e rimuovere le policy IAM nella IAM User](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) Guide.*

### Esportazione in AWS IoT Analytics
<a name="export-streams-to-iot-analytics"></a>

Per creare un flusso che esporta in AWS IoT Analytics, i componenti Greengrass [creano un flusso con una](work-with-streams.md#streammanagerclient-create-message-stream) definizione di esportazione che include uno o più `IoTAnalyticsConfig` oggetti. Questo oggetto definisce le impostazioni di esportazione, come il canale di destinazione, la dimensione del batch, l'intervallo del batch e la priorità.

Quando i componenti Greengrass ricevono dati dai dispositivi, [aggiungono messaggi](work-with-streams.md#streammanagerclient-append-message) che contengono un blob di dati allo stream di destinazione.

Quindi, stream manager esporta i dati in base alle impostazioni del batch e alla priorità definite nelle configurazioni di esportazione dello stream.

## Flussi di dati Amazon Kinesis
<a name="export-to-kinesis"></a>

Stream Manager supporta le esportazioni automatiche verso Amazon Kinesis Data Streams. <a name="aks-export-destination"></a>Kinesis Data Streams viene comunemente utilizzato per aggregare dati di grandi volumi e caricarli in un data warehouse o cluster. MapReduce Per ulteriori informazioni, consulta [Cos'è Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/what-is-this-service.html)? nella *Amazon Kinesis Developer Guide*. 

Nell'SDK Stream Manager, i componenti Greengrass utilizzano per definire `KinesisConfig` la configurazione di esportazione per questo tipo di destinazione. Per ulteriori informazioni, consultate il riferimento SDK per la lingua di destinazione:
+ [KinesisConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.KinesisConfig)nell'SDK Python
+ [KinesisConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/export/KinesisConfig.html)nell'SDK Java
+ [KinesisConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.KinesisConfig.html)nell'SDK Node.js

### Requisiti
<a name="export-to-kinesis-reqs"></a>

Questa destinazione di esportazione presenta i seguenti requisiti:
+ I flussi di destinazione in Kinesis Data Streams devono trovarsi nello Regione AWS stesso dispositivo principale Account AWS Greengrass.
+ (Consigliato) Stream manager v2.2.1 migliora le prestazioni di esportazione dei flussi verso destinazioni Kinesis Data Streams. Per utilizzare i miglioramenti di quest'ultima versione, aggiorna il [componente di gestione degli stream](stream-manager-component.md) alla versione 2.2.1 e utilizza la `kinesis:ListShards` politica nel ruolo di scambio di token [Greengrass](device-service-role.md). 
+ È [Autorizza i dispositivi principali a interagire con i servizi AWS](device-service-role.md) necessario consentire l'`kinesis:PutRecords`autorizzazione per indirizzare i flussi di dati. Esempio:

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "kinesis:PutRecords"
        ],
        "Resource": [
          "arn:aws:kinesis:us-east-1:123456789012:stream/stream_1_name",
          "arn:aws:kinesis:us-east-1:123456789012:stream/stream_2_name"
        ]
      }
    ]
  }
  ```

------

  <a name="wildcards-grant-granular-conditional-access"></a>È possibile concedere un accesso granulare o condizionale alle risorse, ad esempio utilizzando uno schema di denominazione con caratteri jolly`*`. *Per ulteriori informazioni, consulta [Aggiungere e rimuovere le policy IAM nella IAM User](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) Guide.*

### Esportazione in Kinesis Data Streams
<a name="export-streams-to-kinesis"></a>

Per creare un flusso che esporta in Kinesis Data Streams, i [componenti Greengrass creano](work-with-streams.md#streammanagerclient-create-message-stream) un flusso con una definizione di esportazione che include uno o più oggetti. `KinesisConfig` Questo oggetto definisce le impostazioni di esportazione, come il flusso di dati di destinazione, la dimensione del batch, l'intervallo del batch e la priorità.

Quando i componenti Greengrass ricevono dati dai dispositivi, [aggiungono messaggi](work-with-streams.md#streammanagerclient-append-message) che contengono un blob di dati allo stream di destinazione. Quindi, stream manager esporta i dati in base alle impostazioni del batch e alla priorità definite nelle configurazioni di esportazione dello stream. 

Stream Manager genera un UUID univoco e casuale come chiave di partizione per ogni record caricato su Amazon Kinesis. 

## AWS IoT SiteWise proprietà degli asset
<a name="export-to-iot-sitewise"></a>

Stream manager supporta le esportazioni automatiche verso AWS IoT SiteWise. <a name="itsw-export-destination"></a>AWS IoT SiteWise consente di raccogliere, organizzare e analizzare dati provenienti da apparecchiature industriali su larga scala. Per ulteriori informazioni, consulta [Cos'è AWS IoT SiteWise?](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/what-is-sitewise.html) nella *Guida AWS IoT SiteWise per l'utente*. 

Nell'SDK Stream Manager, i componenti Greengrass utilizzano per definire `IoTSiteWiseConfig` la configurazione di esportazione per questo tipo di destinazione. Per ulteriori informazioni, consultate il riferimento SDK per la lingua di destinazione:
+ [Io TSite WiseConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.IoTSiteWiseConfig) nell'SDK Python
+ [Io TSite WiseConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/export/IoTSiteWiseConfig.html) nell'SDK Java
+ [Io TSite WiseConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.IoTSiteWiseConfig.html) nell'SDK Node.js

**Nota**  
AWS fornisce anche AWS IoT SiteWise componenti che offrono una soluzione predefinita che è possibile utilizzare per lo streaming di dati da fonti OPC-UA. Per ulteriori informazioni, consulta [Collettore IoT SiteWise OPC UA](iotsitewise-opcua-collector-component.md).

### Requisiti
<a name="export-to-iot-sitewise-reqs"></a>

Questa destinazione di esportazione presenta i seguenti requisiti:
+ Le proprietà degli asset di destinazione AWS IoT SiteWise devono trovarsi nello stesso Account AWS Regione AWS dispositivo principale di Greengrass.
**Nota**  
*Per l'elenco dei sistemi AWS IoT SiteWise supportati, consulta Regione AWS gli [AWS IoT SiteWise endpoint e le quote nella AWS Guida](https://docs.aws.amazon.com/general/latest/gr/iot-sitewise.html#iot-sitewise_region) generale.*
+ [Autorizza i dispositivi principali a interagire con i servizi AWS](device-service-role.md)Devono consentire l'`iotsitewise:BatchPutAssetPropertyValue`autorizzazione per indirizzare le proprietà degli asset. La seguente politica di esempio utilizza la chiave `iotsitewise:assetHierarchyPath` condition per concedere l'accesso a una risorsa principale di destinazione e ai suoi figli. Puoi rimuoverla `Condition` dalla policy per consentire l'accesso a tutte le tue AWS IoT SiteWise risorse o specificare ARNs singole risorse.

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
         "Effect": "Allow",
         "Action": "iotsitewise:BatchPutAssetPropertyValue",
         "Resource": "*",
         "Condition": {
           "StringLike": {
             "iotsitewise:assetHierarchyPath": [
               "/root node asset ID",
               "/root node asset ID/*"
             ]
           }
         }
      }
    ]
  }
  ```

------

  <a name="wildcards-grant-granular-conditional-access"></a>Puoi concedere un accesso granulare o condizionale alle risorse, ad esempio utilizzando uno schema di denominazione con caratteri jolly`*`. *Per ulteriori informazioni, consulta [Aggiungere e rimuovere le policy IAM nella IAM User](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) Guide.*

  Per importanti informazioni sulla sicurezza, consulta [ BatchPutAssetPropertyValue l'autorizzazione](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-batchputassetpropertyvalue-action) nella *Guida AWS IoT SiteWise per l'utente*.

### Esportazione in AWS IoT SiteWise
<a name="export-streams-to-sitewise"></a>

Per creare un flusso che esporta in AWS IoT SiteWise, i componenti Greengrass [creano un flusso con una](work-with-streams.md#streammanagerclient-create-message-stream) definizione di esportazione che include uno o più `IoTSiteWiseConfig` oggetti. Questo oggetto definisce le impostazioni di esportazione, come la dimensione del batch, l'intervallo del batch e la priorità.

Quando i componenti Greengrass ricevono dati sulle proprietà degli asset dai dispositivi, aggiungono messaggi che contengono i dati allo stream di destinazione. I messaggi sono `PutAssetPropertyValueEntry` oggetti serializzati in formato JSON che contengono valori di proprietà per una o più proprietà degli asset. Per ulteriori informazioni, consulta [Aggiungi](work-with-streams.md#streammanagerclient-append-message-sitewise) messaggio per le destinazioni di esportazione. AWS IoT SiteWise 

**Nota**  
<a name="BatchPutAssetPropertyValue-data-reqs"></a>Quando invii dati a AWS IoT SiteWise, i tuoi dati devono soddisfare i requisiti dell'`BatchPutAssetPropertyValue`azione. Per ulteriori informazioni, consulta [BatchPutAssetPropertyValue](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_BatchPutAssetPropertyValue.html) nella *documentazione di riferimento dell’API AWS IoT SiteWise *.

Quindi, stream manager esporta i dati in base alle impostazioni del batch e alla priorità definite nelle configurazioni di esportazione dello stream.

Puoi modificare le impostazioni dello stream manager e la logica dei componenti Greengrass per progettare la tua strategia di esportazione. Esempio:
+ Per esportazioni quasi in tempo reale, impostate impostazioni ridotte per la dimensione del batch e l'intervallo e aggiungete i dati allo stream quando vengono ricevuti.
+ Per ottimizzare il batching, mitigare i vincoli di larghezza di banda o ridurre al minimo i costi, i componenti Greengrass possono raggruppare i punti dati timestamp-quality-value (TQV) ricevuti per una singola proprietà dell'asset prima di aggiungere i dati allo stream. Una strategia consiste nell'inserire in un unico messaggio le voci relative a un massimo di 10 diverse combinazioni proprietà-asset, o alias di proprietà, anziché inviare più di una voce per la stessa proprietà. [Questo aiuta lo stream manager a rimanere entro le quote.AWS IoT SiteWise](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/quotas.html)

## Oggetti Amazon S3
<a name="export-to-s3"></a>

Stream Manager supporta le esportazioni automatiche verso Amazon S3. <a name="s3-export-destination"></a>Puoi usare Amazon S3 per archiviare e recuperare grandi quantità di dati. Per ulteriori informazioni, consulta [Cos'è Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html)? nella *Guida per sviluppatori di Amazon Simple Storage Service*. 

Nell'SDK Stream Manager, i componenti Greengrass utilizzano per definire `S3ExportTaskExecutorConfig` la configurazione di esportazione per questo tipo di destinazione. Per ulteriori informazioni, consultate il riferimento SDK per la lingua di destinazione:
+ [S3 ExportTaskExecutorConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.S3ExportTaskExecutorConfig) nell'SDK Python
+ [S3 nell'SDK Java ExportTaskExecutorConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/export/S3ExportTaskExecutorConfig.html)
+ [S3 ExportTaskExecutorConfig](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.S3ExportTaskExecutorConfig.html) nell'SDK Node.js

### Requisiti
<a name="export-to-s3-reqs"></a>

Questa destinazione di esportazione presenta i seguenti requisiti:
+ I bucket Amazon S3 di Target devono trovarsi nello stesso dispositivo Account AWS principale Greengrass.
+ Se una funzione Lambda eseguita in modalità **contenitore Greengrass** scrive file di input in una directory di file di input, è necessario montare la directory come volume nel contenitore con autorizzazioni di scrittura. Ciò garantisce che i file vengano scritti nel file system root e siano visibili al componente stream manager, che viene eseguito all'esterno del contenitore.
+ Se un componente del contenitore Docker scrive file di input in una directory di file di input, è necessario montare la directory come volume nel contenitore con autorizzazioni di scrittura. Ciò garantisce che i file vengano scritti nel file system root e siano visibili al componente stream manager, che viene eseguito all'esterno del contenitore.
+ [Autorizza i dispositivi principali a interagire con i servizi AWS](device-service-role.md)Deve consentire le seguenti autorizzazioni per i bucket di destinazione. Esempio:

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "s3:PutObject",
          "s3:AbortMultipartUpload",
          "s3:ListMultipartUploadParts"
        ],
        "Resource": [
          "arn:aws:s3:::bucket-1-name/*",
          "arn:aws:s3:::bucket-2-name/*"
        ]
      }
    ]
  }
  ```

------

  <a name="wildcards-grant-granular-conditional-access"></a>È possibile concedere un accesso granulare o condizionale alle risorse, ad esempio utilizzando uno schema di denominazione con caratteri jolly. `*` *Per ulteriori informazioni, consulta [Aggiungere e rimuovere le policy IAM nella IAM User](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) Guide.*

### Esportazione su Amazon S3
<a name="export-streams-to-s3"></a>

Per creare uno stream che esporta in Amazon S3, i componenti Greengrass utilizzano l'`S3ExportTaskExecutorConfig`oggetto per configurare la politica di esportazione. La policy definisce le impostazioni di esportazione, come la soglia e la priorità di caricamento multiparte. Per le esportazioni di Amazon S3, stream manager carica i dati che legge dai file locali sul dispositivo principale. Per avviare un caricamento, i componenti Greengrass aggiungono un'attività di esportazione allo stream di destinazione. L'attività di esportazione contiene informazioni sul file di input e sull'oggetto Amazon S3 di destinazione. Stream Manager esegue le attività nella sequenza in cui vengono aggiunte allo stream.

**Nota**  
 <a name="bucket-not-key-must-exist"></a>Il bucket di destinazione deve già esistere nel tuo. Account AWS Se non esiste un oggetto per la chiave specificata, lo stream manager crea l'oggetto per te. 

Stream manager utilizza la proprietà della soglia di caricamento [multiparte, l'impostazione della dimensione minima](configure-stream-manager.md#stream-manager-minimum-part-size) della parte e la dimensione del file di input per determinare come caricare i dati. La soglia di caricamento in più parti deve essere maggiore o uguale alla dimensione minima della parte. Se desideri caricare dati in parallelo, puoi creare più stream.

Le chiavi che specificano gli oggetti Amazon S3 di destinazione possono includere DateTimeFormatter stringhe [Java](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) valide nei segnaposto. `!{timestamp:value}` Puoi utilizzare questi segnaposto con timestamp per partizionare i dati in Amazon S3 in base all'ora in cui i dati del file di input sono stati caricati. Ad esempio, il seguente nome di chiave si risolve in un valore come. `my-key/2020/12/31/data.txt`

```
my-key/!{timestamp:YYYY}/!{timestamp:MM}/!{timestamp:dd}/data.txt
```

**Nota**  
Se desideri monitorare lo stato dell'esportazione di uno stream, crea prima uno stream di stato e poi configura il flusso di esportazione per utilizzarlo. Per ulteriori informazioni, consulta [Monitora le attività di esportazione](#monitor-export-status-s3).

#### Gestisci i dati di input
<a name="manage-s3-input-data"></a>

Puoi creare codice utilizzato dalle applicazioni IoT per gestire il ciclo di vita dei dati di input. Il seguente flusso di lavoro di esempio mostra come utilizzare i componenti Greengrass per gestire questi dati.

1. Un processo locale riceve dati da dispositivi o periferiche e quindi li scrive su file in una directory sul dispositivo principale. Questi sono i file di input per lo stream manager.

1. Un componente Greengrass analizza la directory e [aggiunge un'attività di esportazione](work-with-streams.md#streammanagerclient-append-message-export-task) allo stream di destinazione quando viene creato un nuovo file. L'attività è un `S3ExportTaskDefinition` oggetto serializzato in JSON che specifica l'URL del file di input, il bucket e la chiave Amazon S3 di destinazione e i metadati utente opzionali.

1. Stream Manager legge il file di input ed esporta i dati in Amazon S3 nell'ordine delle attività aggiunte. <a name="bucket-not-key-must-exist"></a>Il bucket di destinazione deve già esistere nel tuo. Account AWS Se non esiste un oggetto per la chiave specificata, lo stream manager crea l'oggetto per te. 

1. Il componente Greengrass [legge i messaggi](work-with-streams.md#streammanagerclient-read-messages) da un flusso di stato per monitorare lo stato dell'esportazione. Una volta completate le attività di esportazione, il componente Greengrass può eliminare i file di input corrispondenti. Per ulteriori informazioni, consulta [Monitora le attività di esportazione](#monitor-export-status-s3).

### Monitora le attività di esportazione
<a name="monitor-export-status-s3"></a>

Puoi creare codice utilizzato dalle applicazioni IoT per monitorare lo stato delle esportazioni Amazon S3. I componenti Greengrass devono creare un flusso di stato e quindi configurare il flusso di esportazione per scrivere aggiornamenti di stato nel flusso di stato. Un singolo flusso di stato può ricevere aggiornamenti di stato da più flussi esportati in Amazon S3.

Innanzitutto, [crea uno stream](work-with-streams.md#streammanagerclient-create-message-stream) da utilizzare come flusso di stato. Puoi configurare le dimensioni e le politiche di conservazione dello stream per controllare la durata dei messaggi di stato. Esempio:
+ `Persistence`Imposta su `Memory` se non desideri archiviare i messaggi di stato.
+ Impostato `StrategyOnFull` in `OverwriteOldestData` modo che i nuovi messaggi di stato non vadano persi.

Quindi, crea o aggiorna il flusso di esportazione per utilizzare il flusso di stato. In particolare, imposta la proprietà di configurazione dello stato della configurazione di `S3ExportTaskExecutorConfig` esportazione dello stream. Questa impostazione indica al gestore dello stream di scrivere messaggi di stato sulle attività di esportazione nello stream di stato. Nell'`StatusConfig`oggetto, specificate il nome del flusso di stato e il livello di verbosità. I seguenti valori supportati vanno da least verbose (`ERROR`) a most verbose (). `TRACE` Il valore predefinito è `INFO`.
+ `ERROR`
+ `WARN`
+ `INFO`
+ `DEBUG`
+ `TRACE`

Il seguente flusso di lavoro di esempio mostra come i componenti Greengrass potrebbero utilizzare un flusso di stato per monitorare lo stato delle esportazioni.

1. Come descritto nel flusso di lavoro precedente, un componente Greengrass [aggiunge un'attività di esportazione](work-with-streams.md#streammanagerclient-append-message-export-task) a uno stream configurato per scrivere messaggi di stato sulle attività di esportazione in un flusso di stato. L'operazione di aggiunta restituisce un numero di sequenza che rappresenta l'ID dell'attività.

1. Un componente Greengrass [legge i messaggi](work-with-streams.md#streammanagerclient-read-messages) in sequenza dallo stream di stato, quindi filtra i messaggi in base al nome del flusso e all'ID dell'attività o in base a una proprietà dell'attività di esportazione dal contesto del messaggio. Ad esempio, il componente Greengrass può filtrare in base all'URL del file di input dell'attività di esportazione, che è rappresentato dall'`S3ExportTaskDefinition`oggetto nel contesto del messaggio.

   I seguenti codici di stato indicano che un'attività di esportazione ha raggiunto lo stato di completamento:
   + `Success`. Il caricamento è stato completato con successo.
   + `Failure`. Lo stream manager ha riscontrato un errore, ad esempio, il bucket specificato non esiste. Dopo aver risolto il problema, puoi aggiungere nuovamente l'attività di esportazione allo stream.
   + `Canceled`. L'attività è stata interrotta perché la definizione dello stream o dell'esportazione è stata eliminata o il periodo time-to-live (TTL) dell'attività è scaduto.
**Nota**  
L'attività potrebbe anche avere lo stato o. `InProgress` `Warning` Stream manager emette avvisi quando un evento restituisce un errore che non influisce sull'esecuzione dell'attività. Ad esempio, la mancata pulizia di un caricamento parziale restituisce un avviso.

1. Una volta completate le attività di esportazione, il componente Greengrass può eliminare i file di input corrispondenti.

L'esempio seguente mostra come un componente Greengrass potrebbe leggere ed elaborare i messaggi di stato.

------
#### [ Python ]

```
import time
from stream_manager import (
    ReadMessagesOptions,
    Status,
    StatusConfig,
    StatusLevel,
    StatusMessage,
    StreamManagerClient,
)
from stream_manager.util import Util

client = StreamManagerClient()
 
try:
    # Read the statuses from the export status stream
    is_file_uploaded_to_s3 = False
    while not is_file_uploaded_to_s3:
        try:
            messages_list = client.read_messages(
                "StatusStreamName", ReadMessagesOptions(min_message_count=1, read_timeout_millis=1000)
            )
            for message in messages_list:
                # Deserialize the status message first.
                status_message = Util.deserialize_json_bytes_to_obj(message.payload, StatusMessage)

                # Check the status of the status message. If the status is "Success",
                # the file was successfully uploaded to S3.
                # If the status was either "Failure" or "Cancelled", the server was unable to upload the file to S3.
                # We will print the message for why the upload to S3 failed from the status message.
                # If the status was "InProgress", the status indicates that the server has started uploading
                # the S3 task.
                if status_message.status == Status.Success:
                    logger.info("Successfully uploaded file at path " + file_url + " to S3.")
                    is_file_uploaded_to_s3 = True
                elif status_message.status == Status.Failure or status_message.status == Status.Canceled:
                    logger.info(
                        "Unable to upload file at path " + file_url + " to S3. Message: " + status_message.message
                    )
                    is_file_uploaded_to_s3 = True
            time.sleep(5)
        except StreamManagerException:
            logger.exception("Exception while running")
except StreamManagerException:
    pass
    # Properly handle errors.
except ConnectionError or asyncio.TimeoutError:
    pass
    # Properly handle errors.
```

[Riferimento all'SDK Python: read\$1messages \$1 [StatusMessage](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.data.html#stream_manager.data.StatusMessage)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-python/_apidoc/stream_manager.streammanagerclient.html#stream_manager.streammanagerclient.StreamManagerClient.read_messages)

------
#### [ Java ]

```
import com.amazonaws.greengrass.streammanager.client.StreamManagerClient;
import com.amazonaws.greengrass.streammanager.client.StreamManagerClientFactory;
import com.amazonaws.greengrass.streammanager.client.utils.ValidateAndSerialize;
import com.amazonaws.greengrass.streammanager.model.ReadMessagesOptions;
import com.amazonaws.greengrass.streammanager.model.Status;
import com.amazonaws.greengrass.streammanager.model.StatusConfig;
import com.amazonaws.greengrass.streammanager.model.StatusLevel;
import com.amazonaws.greengrass.streammanager.model.StatusMessage;

 try (final StreamManagerClient client = StreamManagerClientFactory.standard().build()) {
    try {
        boolean isS3UploadComplete = false;
        while (!isS3UploadComplete) {
            try {
                // Read the statuses from the export status stream
                List<Message> messages = client.readMessages("StatusStreamName",
                    new ReadMessagesOptions().withMinMessageCount(1L).withReadTimeoutMillis(1000L));
                for (Message message : messages) {
                    // Deserialize the status message first.
                    StatusMessage statusMessage = ValidateAndSerialize.deserializeJsonBytesToObj(message.getPayload(), StatusMessage.class);
                    // Check the status of the status message. If the status is "Success", the file was successfully uploaded to S3.
                    // If the status was either "Failure" or "Canceled", the server was unable to upload the file to S3.
                    // We will print the message for why the upload to S3 failed from the status message.
                    // If the status was "InProgress", the status indicates that the server has started uploading the S3 task.
                    if (Status.Success.equals(statusMessage.getStatus())) {
                        System.out.println("Successfully uploaded file at path " + FILE_URL + " to S3.");
                        isS3UploadComplete = true;
                     } else if (Status.Failure.equals(statusMessage.getStatus()) || Status.Canceled.equals(statusMessage.getStatus())) {
                        System.out.println(String.format("Unable to upload file at path %s to S3. Message %s",
                            statusMessage.getStatusContext().getS3ExportTaskDefinition().getInputUrl(),
                            statusMessage.getMessage()));
                        sS3UploadComplete = true;
                    }
                }
            } catch (StreamManagerException ignored) {
            } finally {
                // Sleep for sometime for the S3 upload task to complete before trying to read the status message.
                Thread.sleep(5000);
            }
        } catch (e) {
        // Properly handle errors.
    }
} catch (StreamManagerException e) {
    // Properly handle exception.
}
```

Riferimento a Java SDK: [ReadMessages \$1 [StatusMessage](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/model/StatusMessage.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-java/com/amazonaws/greengrass/streammanager/client/StreamManagerClient.html#readMessages-java.lang.String-com.amazonaws.greengrass.streammanager.model.ReadMessagesOptions-)

------
#### [ Node.js ]

```
const {
    StreamManagerClient, ReadMessagesOptions,
    Status, StatusConfig, StatusLevel, StatusMessage,
    util,
} = require(*'aws-greengrass-stream-manager-sdk'*);

const client = new StreamManagerClient();
client.onConnected(async () => {
    try {
        let isS3UploadComplete = false;
        while (!isS3UploadComplete) {
            try {
                // Read the statuses from the export status stream
                const messages = await c.readMessages("StatusStreamName",
                    new ReadMessagesOptions()
                        .withMinMessageCount(1)
                        .withReadTimeoutMillis(1000));

                messages.forEach((message) => {
                    // Deserialize the status message first.
                    const statusMessage = util.deserializeJsonBytesToObj(message.payload, StatusMessage);
                    // Check the status of the status message. If the status is 'Success', the file was successfully uploaded to S3.
                    // If the status was either 'Failure' or 'Cancelled', the server was unable to upload the file to S3.
                    // We will print the message for why the upload to S3 failed from the status message.
                    // If the status was "InProgress", the status indicates that the server has started uploading the S3 task.
                    if (statusMessage.status === Status.Success) {
                        console.log(`Successfully uploaded file at path ${FILE_URL} to S3.`);
                        isS3UploadComplete = true;
                    } else if (statusMessage.status === Status.Failure || statusMessage.status === Status.Canceled) {
                        console.log(`Unable to upload file at path ${FILE_URL} to S3. Message: ${statusMessage.message}`);
                        isS3UploadComplete = true;
                    }
                });
                // Sleep for sometime for the S3 upload task to complete before trying to read the status message.
                await new Promise((r) => setTimeout(r, 5000));
            } catch (e) {
                // Ignored
            }
    } catch (e) {
        // Properly handle errors.
    }
});
client.onError((err) => {
    // Properly handle connection errors.
    // This is called only when the connection to the StreamManager server fails.
});
```

Riferimento all'SDK Node.js: [ReadMessages \$1 [StatusMessage](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StatusMessage.html)](https://aws-greengrass.github.io/aws-greengrass-stream-manager-sdk-js/aws-greengrass-core-sdk.StreamManager.StreamManagerClient.html#readMessages)

------