如何使用KCL确定特定分区键的分片ID?

bur*_*mre 3 amazon-web-services amazon-kinesis

PutRequestAPI使用分区键来确定记录的分片ID.即使PutRequest包含shard id 的响应,它也不可靠,因为分片是可拆分的,因此记录可以移动到新的分片.我找不到一种方法来确定消费者端特定分区键的分片ID.

AWS似乎将分区键映射到128位整数键,但文档中没有解释散列算法.我想要做的是处理具有特定分区键的Kinesis流中的记录,这意味着它们将位于特定分片中,以便我可以只获取特定分片中的数据但我找不到合适的API在文档中.

rya*_*ner 7

根据文档,使用的散列算法是MD5.

MD5散列函数用于将分区键映射到128位整数值,并使用分片的散列键范围将关联的数据记录映射到分片.

http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html

在您的情况下,如果您知道要为其标识相应分片的分区键,则需要执行以下两项操作:

  1. 计算分区键的MD5哈希值
  2. 浏览分片列表以查找其散列键范围包括在第一步中计算的散列值的分片.

这里有一些代码片段可以帮助您:

MD5哈希作为BigInteger

String partitionKey = "YourKnownKey";
byte[] partitionBytes = partitionKey.getBytes("UTF-8");
byte[] hashBytes = MessageDigest.getInstance("MD5").digest(partitionBytes);
BigInteger biPartitionKey = new BigInteger(1, hashBytes);
Run Code Online (Sandbox Code Playgroud)

查找分区键的分片

Shard shardYouAreAfter = null;
String streamName = "YourStreamName";
StreamDescription streamDesc =  client.describeStream(streamName).getStreamDescription();
List<Shard> shards =  streamDesc.getShards();
for(Shard shard : shards){
        BigInteger startingHashKey = new BigInteger(shard.getHashKeyRange().getStartingHashKey());
        BigInteger endingHashKey = new BigInteger(shard.getHashKeyRange().getEndingHashKey());
        if(startingHashKey.compareTo(biPartKey) <= 0 &&
                endingHashKey.compareTo(biPartKey) >=0) {
            shardYouAreAfter = shard;
            break;
        }
}
Run Code Online (Sandbox Code Playgroud)

如果您已经拆分和/或合并分片,事情会变得复杂一些.以上假设您只存在活动分片.