Skip to content

30 .net core使用AWS DynamoDb

Jinxin Chen edited this page Dec 11, 2019 · 1 revision

本文介绍如何在 .net core访问AWS DynamoDb

下载 local DynamoDb

https://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html

注:即使是local db,也需要配置凭证才能正确连接,并且要声明region。

查看region,任何一个都可以

https://docs.aws.amazon.com/general/latest/gr/rande.html

下载 AWS CLI

https://aws.amazon.com/cn/cli/

配置凭证

aws configure

然后输入事先在IAM中建立的user的key和Secret即可。

验证连接

aws dynamodb list-tables --region eu-west-1 --endpoint-url http://localhost:8000

输出如下内容即成功:

{
    "TableNames": []
}

创建项目及依赖

dotnet new console
dotnet add package AWSSDK.DynamoDBv2

使用高级接口

示例程序:

[DynamoDBTable("TinyUrl")]
public class TinyUrl
{
    [DynamoDBHashKey]
    public string TinyId { get; set; }
    public string Url { get; set; }
}
static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
    AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
    // Set the endpoint URL
    clientConfig.ServiceURL = "http://localhost:8000";
    AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);

    var response = client.CreateTableAsync("TinyUrl", new List<Amazon.DynamoDBv2.Model.KeySchemaElement>(){
        new Amazon.DynamoDBv2.Model.KeySchemaElement()
        {
            AttributeName = "TinyId",
            KeyType = KeyType.HASH
        }
    }, new List<Amazon.DynamoDBv2.Model.AttributeDefinition>(){
        new Amazon.DynamoDBv2.Model.AttributeDefinition()
        {
            AttributeName = "TinyId",
            AttributeType = ScalarAttributeType.S
        }
    },
    provisionedThroughput: new ProvisionedThroughput
    {
        ReadCapacityUnits = 10,
        WriteCapacityUnits = 5
    }).GetAwaiter().GetResult();

    DynamoDBContext context = new DynamoDBContext(client);

    var id = Guid.NewGuid().ToString();

    context.SaveAsync<TinyUrl>(new TinyUrl() { TinyId = id, Url = "www.baidu.com" }).GetAwaiter().GetResult();

    var result = context.LoadAsync<TinyUrl>(id).GetAwaiter().GetResult();

}

使用模板建立 Project

Amazon提供了.net core的项目模板,可以直接建立 Serverless 的项目,省去了自己配置的开销,方法如下:

  1. 安装lambda tool工具

    dotnet new -i Amazon.Lambda.Templates

  2. 建立项目

    dotnet new lambda.EmptyFunction --name MyFunction --profile default --region ap-southeast-1

  3. 安装aws lambda工具集

    dotnet tool install -g Amazon.Lambda.Tools

  4. 利用工具发布lambda function

    dotnet lambda deploy-function MyFunction –-function-role role

  5. 测试

    dotnet lambda invoke-function MyFunction --payload "Just Checking If Everything is OK" --region ap-southeast-1

参考

Clone this wiki locally