-
Notifications
You must be signed in to change notification settings - Fork 0
30 .net core使用AWS DynamoDb
Jinxin Chen edited this page Dec 11, 2019
·
1 revision
本文介绍如何在 .net core访问AWS 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
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();
}
Amazon提供了.net core的项目模板,可以直接建立 Serverless 的项目,省去了自己配置的开销,方法如下:
-
安装lambda tool工具
dotnet new -i Amazon.Lambda.Templates
-
建立项目
dotnet new lambda.EmptyFunction --name MyFunction --profile default --region ap-southeast-1
-
安装aws lambda工具集
dotnet tool install -g Amazon.Lambda.Tools
-
利用工具发布lambda function
dotnet lambda deploy-function MyFunction –-function-role role
-
测试
dotnet lambda invoke-function MyFunction --payload "Just Checking If Everything is OK" --region ap-southeast-1