我可以在sqs中使用相同的sqs客户端来接收消息吗?

时间:2019-12-16 09:03:21

标签: go amazon-sqs

我可以使用相同的* SQS.client请求消息吗? 在SQS中,使用同一客户端接收消息是否正确, 在SQS示例中,他们使用的是:

func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

svc := sqs.New(sess)

// URL to our queue
qURL := "QueueURL"

result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
    AttributeNames: []*string{
        aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
    },
    MessageAttributeNames: []*string{
        aws.String(sqs.QueueAttributeNameAll),
    },
    QueueUrl:            &qURL,
    MaxNumberOfMessages: aws.Int64(10),
    VisibilityTimeout:   aws.Int64(60), // 60 seconds
    WaitTimeSeconds:     aws.Int64(0),
})
if err != nil {
    fmt.Println("Error", err)
    return
}
if len(result.Messages) == 0 {
    fmt.Println("Received no messages")
    return
}

fmt.Printf("Success: %+v\n", result.Messages)
}

我可以将svc存储在内存中,以后再调用接收消息吗?

我知道以下工作,问题是使用这种模式是否正确:

func createSqsSvc(region string) (*sqs.SQS, error) {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String(region)},
    )
    if err != nil {
        return nil, err
    }

    svc := sqs.New(sess)
    return svc, nil
}

//ReceiveMessages from sqs
func receiveMessagesWithSVC(queueName string, region string, svc *sqs.SQS) ([]*sqs.Message, error) {
    // URL to our queue
    qURL := queueName

    result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
        AttributeNames: []*string{
            aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
        },
        MessageAttributeNames: []*string{
            aws.String(sqs.QueueAttributeNameAll),
        },
        QueueUrl:            &qURL,
        MaxNumberOfMessages: aws.Int64(10),
        VisibilityTimeout:   aws.Int64(1), // 60 seconds
        WaitTimeSeconds:     aws.Int64(0),
    })
    if err != nil {
        fmt.Println("Error", err)
        return nil, err
    }
    if len(result.Messages) == 0 {
        fmt.Println("Received no messages")
        return nil, fmt.Errorf("Received no messages")
    }
    fmt.Println("Received messages")
    fmt.Println(result.Messages)

    return result.Messages, nil
}

这有效吗? 还是应该在请求之间创建一个新会话? 此外,我可以将同一会话用于不同的队列吗?

0 个答案:

没有答案