簡體   English   中英

將數據移動到 Amazon Kinesis 時出錯(成員的長度必須小於或等於 1048576)

[英]Error while moving data to Amazon Kinesis (Member must have length less than or equal to 1048576)

在將 Mysql 數據庫中存在的數據移動到 Amazon Kinesis 時,我的 python 代碼出現以下錯誤。 此錯誤可能是由於表中存在大量行。它適用於行較少的表。 有沒有辦法解決這個錯誤? 請指教。

錯誤:botocore.exceptions.ClientError:調用 PutRecord 操作時發生錯誤 (ValidationException):檢測到 1 個驗證錯誤:“數據”處的值未能滿足約束:成員的長度必須小於或等於 1048576。

下面是我正在使用的 python 代碼

from contextlib import closing
from datetime import datetime
import json
import mysql.connector as sql
import boto3
import os
DB_NAME = 'test'
DB_USER = 'root'
DB_PASS = 'xxx'
os.environ['AWS_PROFILE'] = "kinesis_developer"
kinesis = boto3.client('kinesis',region_name='ap-southeast-1')

def get_tables(cursor):
     cursor.execute('SHOW tables')
     return [r[0] for r in cursor.fetchall()] 

def get_rows_as_dicts(cursor, table):
     cursor.execute('select * from {}'.format(table))
     columns = [d[0] for d in cursor.description]
     return [dict(zip(columns, row)) for row in cursor.fetchall()]

class dump_date(json.JSONEncoder):
     def default(self, o):
        if isinstance(o, datetime):
           return o.isoformat()

        return json.JSONEncoder.default(self, o)

with closing(sql.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
   dump = {}
   table = input("Enter name of the table to load: ")
   dump[table] = get_rows_as_dicts(cursor, table)
   kinesis.put_record(StreamName="KinesisStreamName", Data=json.dumps(dump,cls=dump_date), PartitionKey="default")
   print(json.dumps(dump,cls=dump_date)) 

根據AWS 文檔,記錄數據的最大長度為 1048576。您遇到的問題與行數沒有直接關系,而是與 object 的字符串大小有關。 如果您嘗試發送更少的行,每行都具有更大的大小,那么您仍然會遇到這個問題。

此代碼拆分數據以適應大小

KINESIS_SIZE_LIMIT = 1000000 # actually, it is 1048576

def send_chunk(chunk, partition_key, stream_name):
    data = json.dumps(chunk, default=str)
    data_size = len(data.encode("utf-8"))

    if data_size > KINESIS_SIZE_LIMIT:
        # If data is too large, we split them in 2 recursively
        new_chunk_size = int(len(chunk) / 2)
        send_chunk(chunk[:new_chunk_size], partition_key, stream_name)
        send_chunk(chunk[new_chunk_size:], partition_key, stream_name)
    else:
        records = [{"Data": data, "PartitionKey": partition_key}]
        kinesis_client.put_records(StreamName=stream_name, Records=records)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM