golang *** 作使用dynamoDb

golang *** 作使用dynamoDb,第1张

一 . dynamoDb介绍

AWS DynamoDB是一种完全托管的无服务器(Serverless)类型的NoSQL数据库。也是一种键-值(key-value)和文档型数据库,基本可以达到毫秒级的响应时间。作为持久数据库,它具有内置的安全性、备份与还原等功能!

二 . dynamoDb安装 本地docker安装:aws文档教程

镜像:docker pull amazon/dynamodb-local
容器:docker run -it -d -p 8000:8000 --name dynamodb-local amazon/dynamodb-local

线上可以直接使用aws,配置aws configure
三 .可视化工具 开源工具:https://github.com/YoyaTeam/dynamodb-manager

命令:docker-compose up -d

aws工具:NoSQL Workbench for Amazon DynamoDB 下载链接 四 .go *** 作dynamoDb

相关sdk:

“github.com/aws/aws-sdk-go/aws” (v2版本在我本地不好使??所以使用的是这个版本)“github.com/aws/aws-sdk-go/service/dynamodb”“github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute”

表结构:

ky:用户ID string类型d: 用户相关数据 []bety类型 1. 连接
var DynamoDbClient *dynamodb.DynamoDB

func Connect(conf *configs.DynamodbConfig) {
	var staticCredentials = credentials.NewStaticCredentials("AccessKeyID", "SecretAccessKey", "SessionToken")

	sess, _ := session.NewSession()
	DynamoDbClient = dynamodb.New(sess, &aws.Config{
		Region:      aws.String("us-west-2"),
		Endpoint:    aws.String("http://localhost:8000"),
		Credentials: staticCredentials,
	})
}

credentials.NewStaticCredentials 可以不用(我是放到一台服务器上的时候报错了,连接不上dynamo,所以增加凭证(随意写就行)

2. 根据id获取用户信息
func GetItem(id int) []byte {
	params := &dynamodb.GetItemInput{
		Key: map[string]*dynamodb.AttributeValue{
			"ky": {
				S: aws.String(strconv.Itoa(id)),
			},
		},
		TableName: aws.String("tableName"),
	}

	resp, err := DynamoDbClient.GetItem(params)
	if err == nil {
		var item []byte
		err := dynamodbattribute.Unmarshal(resp.Item["d"], &item)
	}

	return item 
}
3. 根据id更新用户信息
func UpdateItem(id int, data []byte) bool {
	params := &dynamodb.UpdateItemInput{
		ExpressionAttributeNames: map[string]*string{
			"#D": aws.String("d"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":d": {
				B: data,
			},
		},
		Key: map[string]*dynamodb.AttributeValue{
			"ky": {
				S: aws.String(strconv.Itoa(id)),
			},
		},
		TableName:        aws.String("tableName"),
		UpdateExpression: aws.String("SET #D = :d"),
	}

	_, err = DynamoDbClient.UpdateItem(params)
	if err != nil {
		return false
	}

	return true
}
4. 创建用户
func PutItem(id int, data []byte) bool {
	input := &dynamodb.PutItemInput{
		Item: map[string]*dynamodb.AttributeValue{
			"ky": {
				S: aws.String(strconv.Itoa(id)),
			},
			"d": {
				B: data,
			},
		},
		TableName: aws.String("tableName"),
	}

	_, err = DynamoDbClient.PutItem(input)
	if err != nil {
		return false
	}

	return true
}
5. 删除用户
func DeleteItem(id int) bool {
	input := &dynamodb.DeleteItemInput{
		Key: map[string]*dynamodb.AttributeValue{
			"ky": {
				S: aws.String(strconv.Itoa(id)),
			},
		},
		TableName: aws.String("tableName"),
	}

	_, err := DynamoDbClient.DeleteItem(input)
	if err != nil {
		return false
	}

	return true
}

五 . 其他相关 aws命令 数据库列表:aws dynamodb list-tables --endpoint-url http://localhost:8000创建数据库:aws dynamodb create-table --table-name mmmmm --attribute-definitions AttributeName=uid,AttributeType=S AttributeName=d1,AttributeType=S --key-schema AttributeName=uid,KeyType=HASH --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --endpoint-url http://localhost:8000创建:aws dynamodb put-item --table-name Music --item ‘{“Artist”: {“S”: “No One You Know”}, “SongTitle”: {“S”: “Call Me Today”}, “AlbumTitle”: {“S”: “Somewhat Famous”}, “Awards”: {“N”: “1”}}’ --endpoint-url http://localhost:8000获取:aws dynamodb get-item --table-name u3d_game4_users --key ‘{“ky”: {“N”: “7”}}’ --return-consumed-capacity TOTAL --endpoint-url http://localhost:8000 v2示例
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

type DynamoDBDescribeTableAPI interface {
	DescribeTable(ctx context.Context,
		params *dynamodb.DescribeTableInput,
		optFns ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error)
}

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithRegion("us-west-2"),
		config.WithEndpointResolver(aws.EndpointResolverFunc(
			func(service, region string) (aws.Endpoint, error) {
				return aws.Endpoint{URL: "http://localhost:8000"}, nil
			})),
	)

	table := "Users"

	fmt.Println("----------描述-----------")
	client := dynamodb.NewFromConfig(cfg)
	input := &dynamodb.DescribeTableInput{
		TableName:&table,
	}
	resp, err := GetTableInfo(context.TODO(), client, input)
	if err != nil {
		panic("failed to describe table, " + err.Error())
	}
	fmt.Println("Info about " + table + ":")
	fmt.Println("  #items:     ", resp.Table.ItemCount)
	fmt.Println("  Size (bytes)", resp.Table.TableSizeBytes)
	fmt.Println("  Status:     ", string(resp.Table.TableStatus))


	svc := dynamodb.NewFromConfig(cfg)


	// 查询
	fmt.Println("----------查询--------")
	resp1, err := svc.GetItem(context.TODO(), &dynamodb.GetItemInput{
		Key: map[string]types.AttributeValue{
			"uid": &types.AttributeValueMemberN{Value: "209963"},
		},
		TableName: aws.String(table),
	})
	if err != nil {
		fmt.Printf("failed to get Item, %v\n", err)
	}
	fmt.Println(resp1)

	// 所有表
	fmt.Println("--------所有表--------")
	resp2, err := svc.ListTables(context.TODO(), &dynamodb.ListTablesInput{
		Limit: aws.Int32(5),
	})
	if err != nil {
		fmt.Printf("failed to list tables, %v\n", err)
	}
	fmt.Println("Tables:")
	for _, tableName := range resp2.TableNames {
		fmt.Println(tableName)
	}
}

func GetTableInfo(c context.Context, api DynamoDBDescribeTableAPI, input *dynamodb.DescribeTableInput) (*dynamodb.DescribeTableOutput, error) {
	return api.DescribeTable(c, input)
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994818.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存