Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 无法进行查询API调用,ResourceNotFoundException:无法对不存在的表执行操作 总结_Go_Amazon Dynamodb_Aws Sam_Aws Sam Cli_Amazon Dynamodb Local - Fatal编程技术网

Go 无法进行查询API调用,ResourceNotFoundException:无法对不存在的表执行操作 总结

Go 无法进行查询API调用,ResourceNotFoundException:无法对不存在的表执行操作 总结,go,amazon-dynamodb,aws-sam,aws-sam-cli,amazon-dynamodb-local,Go,Amazon Dynamodb,Aws Sam,Aws Sam Cli,Amazon Dynamodb Local,我正在通过aws SAM制作aws lambda函数 这个函数需要数据库,所以我选择了DynamoDB 现在我正在为AWS SAM和DynamoDB设置本地环境 似乎我成功地设置了本地DynamoDB,但在运行本地aws sam功能时,它无法连接 failed to make Query API call, ResourceNotFoundException: Cannot do operations on a non-existent table 我想知道如何解决这个问题 尝试 我创建了本地

我正在通过
aws SAM
制作
aws lambda
函数
这个函数需要数据库,所以我选择了
DynamoDB

现在我正在为
AWS SAM
DynamoDB
设置本地环境
似乎我成功地设置了本地
DynamoDB
,但在运行本地
aws sam
功能时,它无法连接

failed to make Query API call, ResourceNotFoundException: Cannot do operations on a non-existent table
我想知道如何解决这个问题

尝试 我创建了本地表,并检查了插入的测试数据

❯ aws dynamodb create-table --cli-input-json file://test/positive-line-bot_table.json --endpoint-url http://localhost:8000
TABLEDESCRIPTION        1578904757.61   0       arn:aws:dynamodb:ddblocal:000000000000:table/PositiveLineBotTable       PositiveLineBotTable    0       ACTIVE
ATTRIBUTEDEFINITIONS    Id      N
BILLINGMODESUMMARY      PROVISIONED     0.0
KEYSCHEMA       Id      HASH
PROVISIONEDTHROUGHPUT   0.0     0.0     0       5       5 

❯ aws dynamodb batch-write-item --request-items file://test/positive-line-bot_table_data.json --endpoint-url http://localhost:8000

❯ aws dynamodb list-tables --endpoint-url http://localhost:8000
TABLENAMES      PositiveLineBotTable

❯ aws dynamodb get-item --table-name PositiveLineBotTable --key '{"Id":{"N":"1"}}' --endpoint-url http://localhost:8000
ID      1
NAME    test
但是当我在本地运行
aws sam
时,它似乎没有连接到这个本地
DynamoDB
,尽管这个表在本地确实存在

❯ sam local start-api --env-vars test/env.json
Fetching lambci/lambda:go1.x Docker container image......
Mounting /Users/jpskgc/go/src/line-positive-bot/positive-line-bot as /var/task:ro,delegated inside runtime container
START RequestId: c9f19371-4fea-1e25-09ec-5f628f7fcb7a Version: $LATEST
failed to make Query API call, ResourceNotFoundException: Cannot do operations on a non-existent table
Function 'PositiveLineBotFunction' timed out after 5 seconds
Function returned an invalid response (must include one of: body, headers, multiValueHeaders or statusCode in the response object). Response received: 
2020-01-13 18:46:10 127.0.0.1 - - [13/Jan/2020 18:46:10] "GET /positive HTTP/1.1" 502 -
我想知道如何实际连接到本地
DynamoDB

一些代码 这是Go中的函数代码

主程序包
//进口
func exitWithError(错误错误){
fmt.Fprintln(os.Stderr,err)
操作系统退出(1)
}
类型项结构{
关键点
描述字符串
数据映射[字符串]接口{}
}
类型事件结构{
类型字符串`json:“类型”`
ReplyToken字符串`json:“ReplyToken”`
Source`json:“Source”`
Timestamp int64`json:“Timestamp”`
Message Message`json:“Message”`
}
类型消息结构{
类型字符串`json:“类型”`
ID字符串`json:“ID”`
文本字符串`json:“文本”`
}
类型源结构{
UserID字符串`json:“UserID”`
类型字符串`json:“类型”`
}
func处理程序(请求事件.APIGatewayProxyRequest)(事件.APIGatewayProxyResponse,错误){
端点:=os.Getenv(“DYNAMODB_端点”)
tableName:=os.Getenv(“DYNAMODB_TABLE_NAME”)
sess:=session.Must(session.NewSession())
config:=aws.NewConfig().WithRegion(“ap-northeast-1”)
如果len(端点)>0{
config=config.WithEndpoint(端点)
}
svc:=dynamodb.New(sess,配置)
参数:=&dynamodb.scanport{
TableName:aws.String(TableName),
}
结果,错误:=svc.Scan(参数)
如果错误!=零{
exitWithError(fmt.Errorf(“未能进行查询API调用,%v”,err))
}
项目:=[]项目{}
err=dynamodbattribute.unmarshallistofmap(result.Items和Items)
如果错误!=零{
exitWithError(fmt.Errorf(“未能解组查询结果项,%v”,错误))
}
var words[]字符串
对于i,项:=范围项{
对于k,v:=范围项。数据{
words=附加(words,v.(字符串))
}
}
rand.Seed(time.Now().UnixNano())
i:=rand.Intn(len(字))
单词:=单词[i]
return events.APIGatewayProxyResponse{
正文:字,
状态代码:200,
},零
}
func main(){
lambda.Start(处理程序)
}
这里是
env.json

我尝试将docker.for.mac.host.internal更改为本地ip地址。但这并不能解决问题

{
  "PositiveLineBotFunction": {
    "DYNAMODB_ENDPOINT": "http://docker.for.mac.host.internal:8000",
    "DYNAMODB_TABLE_NAME": "PositiveLineBotTable"
  }
}

这里是
template.yml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  positive-line-bot

Globals:
  Function:
    Timeout: 5

Resources:
  PositiveLineBotFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: positive-line-bot/
      Handler: positive-line-bot
      Runtime: go1.x
      Policies:
        - DynamoDBReadPolicy:
          TableName: !Ref PositiveLineBotTable
      Tracing: Active
      Events:
        CatchAll:
          Type: Api 
          Properties:
            Path: /positive
            Method: GET
      Environment: 
        Variables:
          DYNAMODB_ENDPOINT: ''
          DYNAMODB_TABLE_NAME: ''

  PositiveLineBotTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: 'PositiveLineBotTable'
      AttributeDefinitions:
        - AttributeName: 'Id'
          AttributeType: 'N'
      KeySchema:
        - AttributeName: 'Id'
          KeyType: 'HASH'
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
      BillingMode: PAY_PER_REQUEST

Outputs:
  PositiveLineBotAPI:
    Description: 'API Gateway endpoint URL for Prod environment for PositiveLineBot'
    Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/positive/'
  PositiveLineBotFunction:
    Description: 'PositiveLineBot Lambda Function ARN'
    Value: !GetAtt PositiveLineBotFunction.Arn
  PositiveLineBotFunctionIamRole:
    Description: 'Implicit IAM Role created for PositiveLineBot'
    Value: !GetAtt PositiveLineBotFunction.Arn
这是完整的源代码。

请参见

解决方案由两部分组成:

  • 创建一个docker网络,并使用该网络启动dynamodb本地容器和api
  • 适当调整端点
对我来说,我做到了:

docker network create dynamodb-network
docker run -d -v "$PWD":/dynamodb_local_db -p 8000:8000 --network dynamodb-network --name dynamodb cnadiminti/dynamodb-local
sam local start-api --docker-network dynamodb-network -n env.json
在我的代码中,我引用docker名称作为DNS地址:

const awsRegion = process.env.AWS_REGION || "us-east-2";
const options = {
  region: awsRegion,
};
if (process.env.AWS_SAM_LOCAL) {
  options.endpoint = "http://dynamodb:8000";
}
const docClient = new dynamodb.DocumentClient(options);

你解决了这个问题吗?
const awsRegion = process.env.AWS_REGION || "us-east-2";
const options = {
  region: awsRegion,
};
if (process.env.AWS_SAM_LOCAL) {
  options.endpoint = "http://dynamodb:8000";
}
const docClient = new dynamodb.DocumentClient(options);