• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang dynamodb.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/dynamodb.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: CreateDynamoDBClient

func CreateDynamoDBClient() *dynamodb.DynamoDB {
	var dynamoClient *dynamodb.DynamoDB

	localAddr := os.Getenv("LOCAL_DYNAMO_ADDR") //e.g. export LOCAL_DYNAMO_ADDR=http://localhost:8000
	if localAddr != "" {
		log.Printf("Using local dynamodb address - %s", localAddr)
		dynamoClient = dynamodb.New(&aws.Config{Endpoint: aws.String(localAddr), Region: aws.String("here")})
	} else {
		dynamoClient = dynamodb.New(&aws.Config{Region: aws.String("us-east-1")})
	}

	return dynamoClient
}
开发者ID:xtraclabs,项目名称:roll,代码行数:13,代码来源:dynamo.go


示例2: main

// Worker service which reads from an SQS queue pulls off job messages, processes
// the jobs, and records the results. The service uses environment variables for
// its configuration.
//
// Requires the following environment variables to be set.
//
// * WORKER_QUEUE_URL - The SQS queue URL where the service will read job messages
// from. Job messages are created when S3 notifies the SQS queue that a file has
// been uploaded to a particular bucket.
//
// * WORKER_RESULT_QUEUE_URL - The SQS queue URL where the job results will be
// sent to.
//
// * WORKER_RESULT_TABLENAME - The name of the DynamoDB table result items should
// be recorded to.
//
// Optionally the follow environment variables can be provided.
//
// * AWS_REGION - The AWS region the worker will use for signing and making all
// requests to. This parameter is only optional if the service is running within
// an EC2 instance. If not running in an EC2 instance AWS_REGION is required.
//
// * WORKER_MESSAGE_VISIBILITY - The ammount of time messges will be hidden in
// the SQS job message queue from other services when a service reads that message.
// Will also be used to extend the visibility timeout for long running jobs.
// Defaults to 60s.
//
// * WORKER_COUNT - The number of workers in the worker pool. Defaults to the
// number of virtual CPUs in the system.
//
func main() {
	doneCh := listenForSigInterrupt()

	cfg, err := getConfig()
	if err != nil {
		log.Println("Unable to get config", err)
		os.Exit(1)
	}

	sqsSvc := sqs.New(nil)
	queue := NewJobMessageQueue(cfg.WorkerQueueURL, cfg.MessageVisibilityTimeout, 5, sqsSvc)
	go queue.Listen(doneCh)

	// Job Workers
	resultsCh := make(chan *wordfreq.JobResult, 10)
	workers := NewWorkerPool(cfg.NumWorkers, resultsCh, queue, s3.New(nil))

	// Notifier to notify a Amazon SNS Topic
	notify := NewResultNotifier(sqsSvc, cfg.ResultQueueURL)
	// Recorder to write results to Amazon DynamoDB
	recorder := NewResultRecorder(cfg.ResultTableName, dynamodb.New(nil))

	// Job Progress Collector
	collector := NewResultCollector(notify, recorder, queue)
	go collector.ProcessJobResult(resultsCh)

	// Wait for the workers to complete before continuing on to exit
	workers.WaitForWorkersDone()
	close(resultsCh)

	// Wait for all results to be completed before continuing
	collector.WaitForResults()
}
开发者ID:Tsingson1988,项目名称:aws-go-wordfreq-sample,代码行数:63,代码来源:main.go


示例3: NewDynamoDBClient

// NewDynamoDBClient returns an *dynamodb.Client with a connection to the region
// configured via the AWS_REGION environment variable.
// It returns an error if the connection cannot be made or the table does not exist.
func NewDynamoDBClient(table string) (*Client, error) {
	var c *aws.Config
	if os.Getenv("DYNAMODB_LOCAL") != "" {
		log.Debug("DYNAMODB_LOCAL is set")
		endpoint := "http://localhost:8000"
		c = &aws.Config{
			Endpoint: &endpoint,
		}
	} else {
		c = nil
	}

	session := session.New(c)

	// Fail early, if no credentials can be found
	_, err := session.Config.Credentials.Get()
	if err != nil {
		return nil, err
	}

	d := dynamodb.New(session)

	// Check if the table exists
	_, err = d.DescribeTable(&dynamodb.DescribeTableInput{TableName: &table})
	if err != nil {
		return nil, err
	}
	return &Client{d, table}, nil
}
开发者ID:kelseyhightower,项目名称:confd,代码行数:32,代码来源:client.go


示例4: NewDynamoModule

// here, support a function that maps a given redis key to a dynamodb table key and value field
func NewDynamoModule(keymap KeyMapper) *DynamoModule {

	module := &DynamoModule{}
	cfgdir := "/etc"
	cfg := &module.config
	ok := logging.ReadModuleConfig(cfg, cfgdir, "dynamo") || logging.ReadModuleConfig(cfg, ".", "dynamo")

	sess := session.New(&aws.Config{Region: aws.String("ap-southeast-1")})

	if !ok {
		log.Println("failed to read dynamo config, using defaults")
	} else {
		sess = session.New(&aws.Config{
			Region:     aws.String(cfg.Server.Region),
			Endpoint:   aws.String(cfg.Server.Endpoint),
			DisableSSL: aws.Bool(cfg.Server.DisableSSL),
		})
	}

	module.client = dynamodb.New(sess)
	if keymap != nil {
		module.keyMapper = keymap
	} else {
		module.keyMapper = module.defaultMapper
	}

	if cfg.Server.CacheDuration > 0 {
		logging.Debug.Println("activiating cache, TTL", cfg.Server.CacheDuration)
		module.cache = cache.NewMemoryWithTTL(time.Duration(cfg.Server.CacheDuration) * time.Second)
	}

	return module
}
开发者ID:qzaidi,项目名称:redamo,代码行数:34,代码来源:dynamo.go


示例5: CreateDynamoDbBackend

func CreateDynamoDbBackend(proxy_name string, tablename string, awsConfig *aws.Config) *DynamoDbBackend {
	return &DynamoDbBackend{
		proxy_name: proxy_name,
		tablename:  tablename,
		database:   dynamodb.New(session.New(), awsConfig),
	}
}
开发者ID:brandnetworks,项目名称:tcpproxy,代码行数:7,代码来源:dynamodb.go


示例6: main

func main() {
	svc := dynamodb.New(session.New(), &aws.Config{Region: aws.String("eu-central-1")})

	k := Key{
		Email: "[email protected]",
	}

	item, err := dynamodbattribute.ConvertToMap(k)
	if err != nil {
		panic(err)
	}

	result, err := svc.GetItem(&dynamodb.GetItemInput{
		TableName: aws.String("Users"),
		Key:       item,
	})
	if err != nil {
		panic(err)
	}

	r := Record{}
	err = dynamodbattribute.ConvertFromMap(result.Item, &r)

	fmt.Println(r)
}
开发者ID:proydakov,项目名称:aws-sdk-go-example,代码行数:25,代码来源:dynamodb_get_item.go


示例7: main

func main() {
	svc := dynamodb.New(session.New(), &aws.Config{Region: aws.String("eu-central-1")})

	params := &dynamodb.CreateTableInput{
		TableName: aws.String("ProductCatalog"),
		AttributeDefinitions: []*dynamodb.AttributeDefinition{
			{
				AttributeName: aws.String("Id"),
				AttributeType: aws.String("N"),
			},
		},
		KeySchema: []*dynamodb.KeySchemaElement{
			{
				AttributeName: aws.String("Id"),
				KeyType:       aws.String("HASH"),
			},
		},
		ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
			ReadCapacityUnits:  aws.Int64(5),
			WriteCapacityUnits: aws.Int64(5),
		},
	}
	resp, err := svc.CreateTable(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
开发者ID:proydakov,项目名称:aws-sdk-go-example,代码行数:34,代码来源:dynamodb_create_table.go


示例8: ExampleDynamoDB_ListTables

func ExampleDynamoDB_ListTables() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := dynamodb.New(sess)

	params := &dynamodb.ListTablesInput{
		ExclusiveStartTableName: aws.String("TableName"),
		Limit: aws.Int64(1),
	}
	resp, err := svc.ListTables(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
开发者ID:acquia,项目名称:fifo2kinesis,代码行数:25,代码来源:examples_test.go


示例9: Svc

// Svc configures the DynamoDB service to use
func Svc(opts config.Options) *dynamodb.DynamoDB {
	awsConfig := &aws.Config{Region: aws.String(opts.Storage.AWS.Region)}

	// If a session was passed... (AWS Lambda does this)
	if opts.Storage.AWS.SessionToken != "" {
		os.Setenv("AWS_SESSION_TOKEN", opts.Storage.AWS.SessionToken)
	}

	// Look in a variety of places for AWS credentials. First, try the credentials file set by AWS CLI tool.
	// Note the empty string instructs to look under default file path (different based on OS).
	// This file can have multiple profiles and a default profile will be used unless otherwise configured.
	// See: https://godoc.org/github.com/aws/aws-sdk-go/aws/credentials#SharedCredentialsProvider
	creds := credentials.NewSharedCredentials("", opts.Storage.AWS.CredProfile)
	_, err := creds.Get()
	// If that failed, try environment variables.
	if err != nil {
		// The following are checked:
		// Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
		// Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
		creds = credentials.NewEnvCredentials()
	}

	// If credentials were passed via config, then use those. They will take priority over other methods.
	if opts.Storage.AWS.AccessKeyID != "" && opts.Storage.AWS.SecretAccessKey != "" {
		creds = credentials.NewStaticCredentials(opts.Storage.AWS.AccessKeyID, opts.Storage.AWS.SecretAccessKey, "")
	}
	awsConfig.Credentials = creds

	return dynamodb.New(session.New(awsConfig))
}
开发者ID:tmaiaroto,项目名称:discfg,代码行数:31,代码来源:dynamodb.go


示例10: New

//New creates a new dynamodb connection
func New(publicKey, secretKey string) *DB {
	creds := credentials.NewStaticCredentials(publicKey, secretKey, "")

	return &DB{
		SVC: dynamodb.New(session.New(), aws.NewConfig().WithCredentials(creds).WithRegion("us-east-1")),
	}
}
开发者ID:johnkelly,项目名称:go_samples,代码行数:8,代码来源:db.go


示例11: Main

func Main() {
	var (
		SQS                        *sqs.SQS
		getUserQueueUrlOutput      *sqs.GetQueueUrlOutput
		getContainerQueueUrlOutput *sqs.GetQueueUrlOutput
		UserQueueUrl               *string
		ContainerQueueUrl          *string

		Dynamo *dynamodb.DynamoDB

		socialWorker *workers.SocialWorker
	)

	SQS = sqs.New(&aws.Config{Region: aws.String("cn-north-1")})
	getUserQueueUrlOutput, err := SQS.GetQueueUrl(&sqs.GetQueueUrlInput{QueueName: aws.String(USER_QUEUE_NAME)})
	if err != nil {
		glog.Errorln("Error on connect user queue url:", err.Error())
		return
	}
	UserQueueUrl = getUserQueueUrlOutput.QueueUrl
	getContainerQueueUrlOutput, err = SQS.GetQueueUrl(&sqs.GetQueueUrlInput{QueueName: aws.String(CONTAINER_QUEUE_NAME)})
	if err != nil {
		glog.Errorln("Error on connect container queue url:", err.Error())
		return
	}
	ContainerQueueUrl = getContainerQueueUrlOutput.QueueUrl

	Dynamo = dynamodb.New(&aws.Config{Region: aws.String("cn-north-1")})

	socialWorker = workers.NewSocialWorker(SQS, UserQueueUrl, ContainerQueueUrl, Dynamo)
	socialWorker.Start()
}
开发者ID:luzh0422,项目名称:spider-docker,代码行数:32,代码来源:hypervisor.go


示例12: main

func main() {
	awsSession := session.New()
	awsSession.Config.WithRegion(os.Getenv("AWS_REGION"))

	tree = &dynamotree.Tree{
		TableName: "hstore-example-shortlinks",
		DB:        dynamodb.New(awsSession),
	}
	err := tree.CreateTable()
	if err != nil {
		log.Fatalf("hstore: %s", err)
	}

	goji.Get("/:link", ServeLink)
	goji.Post("/signup", CreateAccount)

	authMux := web.New()
	authMux.Use(RequireAccount)
	authMux.Post("/", CreateLink)
	authMux.Get("/", ListLinks)
	authMux.Delete("/:link", DeleteLink) // TODO(ross): this doesn't work (!)
	goji.Handle("/", authMux)

	goji.Serve()
}
开发者ID:crewjam,项目名称:dynamotree,代码行数:25,代码来源:shortlink.go


示例13: TestReservedCharacters

func (suite *StoreImplTest) TestReservedCharacters(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{
		TableName:        tableName,
		DB:               db,
		SpecialCharacter: "X",
	}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:    "12345",
		Name:  "alice",
		Email: "[email protected]",
	}
	err = s.Put([]string{"Accounts", "12X345"}, &v)
	c.Assert(err, Equals, ErrReservedCharacterInKey)

	v.Xfoo = "cannot be set"
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, Equals, ErrReservedCharacterInAttribute)

	v.Xfoo = ""
	v.FooXBar = "can be set"
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, IsNil)

	err = s.PutLink([]string{"AccountsXEmail", "[email protected]"}, []string{"Accounts", "12345"})
	c.Assert(err, Equals, ErrReservedCharacterInKey)

	err = s.PutLink([]string{"AccountsByEmail", "[email protected]"}, []string{"AccountsX", "12345"})
	c.Assert(err, Equals, ErrReservedCharacterInKey)
}
开发者ID:crewjam,项目名称:dynamotree,代码行数:34,代码来源:dynamodb_test.go


示例14: TestLinkFailures

func (suite *StoreImplTest) TestLinkFailures(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:                  "12345",
		Name:                "alice",
		Email:               "[email protected]",
		UnmarshalFailPlease: true,
	}
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, IsNil)

	err = s.PutLink([]string{"AccountsByEmail", "[email protected]"}, []string{"Accounts", "12345"})
	c.Assert(err, IsNil)

	_, err = s.GetLink([]string{"AccountsByEmail", "missing"})
	c.Assert(err, Equals, ErrNotFound)

	_, err = s.GetLink([]string{"Accounts", "12345"})
	c.Assert(err, Equals, ErrNotLink)
}
开发者ID:crewjam,项目名称:dynamotree,代码行数:25,代码来源:dynamodb_test.go


示例15: benchPutItemParallel

func benchPutItemParallel(p, c int, b *testing.B) {
	svc := dynamodb.New(&aws.Config{
		DisableSSL: aws.Bool(true),
	})

	av, err := dynamodbattribute.ConvertToMap(dbItem{Key: "MyKey", Data: "MyData"})
	if err != nil {
		b.Fatal("expect no ConvertToMap errors", err)
	}
	params := &dynamodb.PutItemInput{
		Item:      av,
		TableName: aws.String(testTableName),
	}
	b.N = c

	b.ResetTimer()
	b.SetParallelism(p)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			_, err = svc.PutItem(params)
			if err != nil {
				b.Error("expect no request errors", err)
			}
		}
	})
}
开发者ID:jloper3,项目名称:amazon-ecs-cli,代码行数:26,代码来源:dynamodb_live_test.go


示例16: main

func main() {
	svc := dynamodb.New(session.New(&aws.Config{Region: aws.String("us-east-1")}))
	jar := &CookieManager{}
	var cookieCount int
	var sleepTime int64
	flag.IntVar(&cookieCount, "count", 10, "collect this many cookies")
	flag.Int64Var(&sleepTime, "sleep", 2, "sleep this many between executions")
	flag.Parse()
	for i := 0; i <= cookieCount; i++ {
		jar.jar = make(map[string][]*http.Cookie)
		if resp, err := GetCookie(jar); err == nil {
			t, _ := time.Parse(timeLongForm, resp.Header["Date"][0])
			time_string := strconv.FormatInt(t.Unix(), 10)
			body := resp.Body
			params := ProcessCookies(&InputItem{*jar, time_string, table_name, ScrapePage(&body)})
			svc.PutItem(params)
		} else {
			fmt.Println("Failed to get a response body.  Will retry after timeout.")
		}
		if i%5 == 0 && i != 0 {
			fmt.Printf("Got %d cookies.\n", i)
		}
		time.Sleep(time.Duration(sleepTime) * time.Second) // lets hold firm 2s for niceness
	}
}
开发者ID:ohrodr,项目名称:2kcookies,代码行数:25,代码来源:2kcookies.go


示例17: Run

func (c *ListTablesCommand) Run(args []string) int {
	var exclusiveStartTableName string
	var limit int

	cmdFlags := flag.NewFlagSet("list-tables", flag.ContinueOnError)
	cmdFlags.Usage = func() { c.Ui.Output(c.Help()) }
	cmdFlags.StringVar(&exclusiveStartTableName, "exclusive-start-table-name", "", "exclusive start table name")
	cmdFlags.IntVar(&limit, "limit", 100, "limit")
	if err := cmdFlags.Parse(args); err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	svc := dynamodb.New(session.New())
	params := &dynamodb.ListTablesInput{
		ExclusiveStartTableName: aws.String(exclusiveStartTableName),
		Limit: limit,
	}

	res, err := svc.ListTables(params)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}
	c.Ui.Output(res)
	return 0
}
开发者ID:hirokazumiyaji,项目名称:dynamodb-cli,代码行数:27,代码来源:list_tables.go


示例18: TestStuff

func (s *FakeDynamoDBTest) TestStuff(c *C) {
	fakeDB, err := New()
	c.Assert(err, IsNil)
	defer fakeDB.Close()
	c.Assert(fakeDB.Port, Not(Equals), 0)

	db := dynamodb.New(session.New(), fakeDB.Config)

	_, err = db.CreateTable(&dynamodb.CreateTableInput{
		TableName: aws.String("frob"),
		KeySchema: []*dynamodb.KeySchemaElement{
			{
				AttributeName: aws.String("Key"),
				KeyType:       aws.String(dynamodb.KeyTypeHash),
			},
		},
		AttributeDefinitions: []*dynamodb.AttributeDefinition{
			&dynamodb.AttributeDefinition{
				AttributeName: aws.String("Key"),
				AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
			},
		},
		ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
			ReadCapacityUnits:  aws.Int64(1),
			WriteCapacityUnits: aws.Int64(1),
		},
	})
	c.Assert(err, IsNil)
}
开发者ID:crewjam,项目名称:fakeaws,代码行数:29,代码来源:dynamodb_test.go


示例19: DynamoTables

// DynamoTables responses dynamodb tables
func DynamoTables() (clusters []*string, e error) {
	resp, err := dynamodb.New(dynamoCfg).ListTables(nil)
	if err != nil {
		return nil, err
	}
	return resp.TableNames, nil
}
开发者ID:supinf,项目名称:reinvent-sessions-api,代码行数:8,代码来源:dynamodb.go


示例20: BenchmarkPutItem

func BenchmarkPutItem(b *testing.B) {
	cfg := aws.Config{
		DisableSSL:  aws.Bool(true),
		Credentials: credentials.NewStaticCredentials("AKID", "SECRET", ""),
	}
	server := successRespServer([]byte(`{}`))
	cfg.Endpoint = aws.String(server.URL)

	svc := dynamodb.New(&cfg)
	svc.Handlers.Send.Clear()
	svc.Handlers.Send.PushBack(func(r *service.Request) {
		r.HTTPResponse = &http.Response{
			StatusCode: http.StatusOK,
			Status:     http.StatusText(http.StatusOK),
			Body:       noopBody,
		}
	})

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		av, err := dynamodbattribute.ConvertToMap(dbItem{Key: "MyKey", Data: "MyData"})
		if err != nil {
			b.Fatal("benchPutItem, expect no ConvertToMap errors", err)
		}
		params := &dynamodb.PutItemInput{
			Item:      av,
			TableName: aws.String("tablename"),
		}
		_, err = svc.PutItem(params)
		if err != nil {
			b.Error("benchPutItem, expect no request errors", err)
		}
	}
}
开发者ID:ahamilton55,项目名称:aws-sdk-go,代码行数:34,代码来源:dynamodb_test.go



注:本文中的github.com/aws/aws-sdk-go/service/dynamodb.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang dynamodb.AttributeValue类代码示例发布时间:2022-05-24
下一篇:
Golang directoryservice.DirectoryService类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap