基于范例,也稍微记录下DynamoDB的用法

STEP1,获取授权,

        和S3的步骤类似,都是AWS的服务,授权这块的逻辑是类似的,建立链接前都需要这一步

        AWSCredentials credentials = null;
        try {
            credentials = new ProfileCredentialsProvider("DynamoDBManager").getCredentials();
            //credentials = new BasicAWSCredentials("AKIAJTY2VTO7V6OVJQOQ", "WFvY61Ft6hLjCcK+YoARvd94BLHRb3oKkP7LJ8X/");
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Cannot load the credentials from the credential profiles file. " +
                    "Please make sure that your credentials file is at the correct " +
                    "location (C:\\Users\\guoyu\\.aws\\credentials), and is in valid format.",
                    e);
        }

STEP2,建立链接

        dynamoDB = new AmazonDynamoDBClient(credentials);
        Region tmpAP_NORTHEAST_1 = Region.getRegion(Regions.AP_NORTHEAST_1);
        dynamoDB.setRegion(tmpAP_NORTHEAST_1);

        是不是发现和S3很像。。。确实很像。。。。

 

STEP3,

建表

            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name").withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(10L));

加数据

            Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara");
            PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);

查数据

            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition()
                .withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1970"));
            scanFilter.put("year", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);

 

以上。

和S3不同的是,DynamoDB可以下载一个本地版本,用于开发目的,当然如果你不介意的话,服务器部署也不是没可能。

需要JAVA环境,我是在VPS上跑的,CentOS7.当然这样别人也能访问编辑了。。。。

类似这样的东西

 

 

最后修改日期: 2017年8月29日

作者