Utilizzare GetRecords con un AWS SDK o CLI - Esempi di codice dell'AWS SDK

Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples GitHub .

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

Utilizzare GetRecords con un AWS SDK o CLI

I seguenti esempi di codice mostrano come utilizzareGetRecords.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

CLI
AWS CLI

Per ottenere record da un frammento

L'get-recordsesempio seguente ottiene i record di dati dallo shard di un flusso di dati Kinesis utilizzando l'iteratore shard specificato.

aws kinesis get-records \ --shard-iterator AAAAAAAAAAF7/0mWD7IuHj1yGv/TKuNgx2ukD5xipCY4cy4gU96orWwZwcSXh3K9tAmGYeOZyLZrvzzeOFVf9iN99hUPw/w/b0YWYeehfNvnf1DYt5XpDJghLKr3DzgznkTmMymDP3R+3wRKeuEw6/kdxY2yKJH0veaiekaVc4N2VwK/GvaGP2Hh9Fg7N++q0Adg6fIDQPt4p8RpavDbk+A4sL9SWGE1

Output:

{ "Records": [], "MillisBehindLatest": 80742000 }

Per ulteriori informazioni, consulta Developing Consumer Using the Kinesis API Data Streams AWS SDK with the for Java nella Amazon Kinesis Data Streams Developer Guide.

  • Per i API dettagli, consulta GetRecordsCommand Reference.AWS CLI

Java
SDKper Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse; import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest; import software.amazon.awssdk.services.kinesis.model.Shard; import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest; import software.amazon.awssdk.services.kinesis.model.GetShardIteratorResponse; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest; import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; import java.util.ArrayList; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class GetRecords { public static void main(String[] args) { final String usage = """ Usage: <streamName> Where: streamName - The Amazon Kinesis data stream to read from (for example, StockTradeStream). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String streamName = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() .region(region) .build(); getStockTrades(kinesisClient, streamName); kinesisClient.close(); } public static void getStockTrades(KinesisClient kinesisClient, String streamName) { String shardIterator; String lastShardId = null; DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder() .streamName(streamName) .build(); List<Shard> shards = new ArrayList<>(); DescribeStreamResponse streamRes; do { streamRes = kinesisClient.describeStream(describeStreamRequest); shards.addAll(streamRes.streamDescription().shards()); if (shards.size() > 0) { lastShardId = shards.get(shards.size() - 1).shardId(); } } while (streamRes.streamDescription().hasMoreShards()); GetShardIteratorRequest itReq = GetShardIteratorRequest.builder() .streamName(streamName) .shardIteratorType("TRIM_HORIZON") .shardId(lastShardId) .build(); GetShardIteratorResponse shardIteratorResult = kinesisClient.getShardIterator(itReq); shardIterator = shardIteratorResult.shardIterator(); // Continuously read data records from shard. List<Record> records; // Create new GetRecordsRequest with existing shardIterator. // Set maximum records to return to 1000. GetRecordsRequest recordsRequest = GetRecordsRequest.builder() .shardIterator(shardIterator) .limit(1000) .build(); GetRecordsResponse result = kinesisClient.getRecords(recordsRequest); // Put result into record list. Result may be empty. records = result.records(); // Print records for (Record record : records) { SdkBytes byteBuffer = record.data(); System.out.printf("Seq No: %s - %s%n", record.sequenceNumber(), new String(byteBuffer.asByteArray())); } } }
PowerShell
Strumenti per PowerShell

Esempio 1: Questo esempio mostra come restituire ed estrarre dati da una serie di uno o più record. L'iteratore supplierd to Get- KINRecord determina la posizione iniziale dei record da restituire, che in questo esempio vengono acquisiti in una variabile, $records. È quindi possibile accedere a ogni singolo record indicizzando la raccolta $records. Supponendo che i dati nel record siano testo con codifica UTF -8, il comando finale mostra come estrarre i dati dall' MemoryStream oggetto e restituirli come testo alla console.

$records $records = Get-KINRecord -ShardIterator "AAAAAAAAAAGIc....9VnbiRNaP"

Output:

MillisBehindLatest NextShardIterator Records ------------------ ----------------- ------- 0 AAAAAAAAAAERNIq...uDn11HuUs {Key1, Key2}
$records.Records[0]

Output:

ApproximateArrivalTimestamp Data PartitionKey SequenceNumber --------------------------- ---- ------------ -------------- 3/7/2016 5:14:33 PM System.IO.MemoryStream Key1 4955986459776...931586
[Text.Encoding]::UTF8.GetString($records.Records[0].Data.ToArray())

Output:

test data from string
  • Per API i dettagli, vedere GetRecordsin AWS Tools for PowerShell Cmdlet Reference.

Python
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

class KinesisStream: """Encapsulates a Kinesis stream.""" def __init__(self, kinesis_client): """ :param kinesis_client: A Boto3 Kinesis client. """ self.kinesis_client = kinesis_client self.name = None self.details = None self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists") def get_records(self, max_records): """ Gets records from the stream. This function is a generator that first gets a shard iterator for the stream, then uses the shard iterator to get records in batches from the stream. Each batch of records is yielded back to the caller until the specified maximum number of records has been retrieved. :param max_records: The maximum number of records to retrieve. :return: Yields the current batch of retrieved records. """ try: response = self.kinesis_client.get_shard_iterator( StreamName=self.name, ShardId=self.details["Shards"][0]["ShardId"], ShardIteratorType="LATEST", ) shard_iter = response["ShardIterator"] record_count = 0 while record_count < max_records: response = self.kinesis_client.get_records( ShardIterator=shard_iter, Limit=10 ) shard_iter = response["NextShardIterator"] records = response["Records"] logger.info("Got %s records.", len(records)) record_count += len(records) yield records except ClientError: logger.exception("Couldn't get records from stream %s.", self.name) raise
  • Per API i dettagli, vedere GetRecordsPython (Boto3) Reference.AWS SDK API

SAP ABAP
SDKper SAP ABAP
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

TRY. oo_result = lo_kns->getrecords( " oo_result is returned for testing purposes. " iv_sharditerator = iv_shard_iterator ). DATA(lt_records) = oo_result->get_records( ). MESSAGE 'Record retrieved.' TYPE 'I'. CATCH /aws1/cx_knsexpirediteratorex . MESSAGE 'Iterator expired.' TYPE 'E'. CATCH /aws1/cx_knsinvalidargumentex . MESSAGE 'The specified argument was not valid.' TYPE 'E'. CATCH /aws1/cx_knskmsaccessdeniedex . MESSAGE 'You do not have permission to perform this AWS KMS action.' TYPE 'E'. CATCH /aws1/cx_knskmsdisabledex . MESSAGE 'KMS key used is disabled.' TYPE 'E'. CATCH /aws1/cx_knskmsinvalidstateex . MESSAGE 'KMS key used is in an invalid state. ' TYPE 'E'. CATCH /aws1/cx_knskmsnotfoundex . MESSAGE 'KMS key used is not found.' TYPE 'E'. CATCH /aws1/cx_knskmsoptinrequired . MESSAGE 'KMS key option is required.' TYPE 'E'. CATCH /aws1/cx_knskmsthrottlingex . MESSAGE 'The rate of requests to AWS KMS is exceeding the request quotas.' TYPE 'E'. CATCH /aws1/cx_knsprovthruputexcdex . MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'. CATCH /aws1/cx_knsresourcenotfoundex . MESSAGE 'Resource being accessed is not found.' TYPE 'E'. ENDTRY.
  • Per API i dettagli, vedi GetRecordsSAPABAPAPIcome riferimento.AWS SDK